Fragment's onActivityResult not called after orientation change

后端 未结 2 1006
庸人自扰
庸人自扰 2021-02-08 08:11

Please note, this question is not a duplicate of the following:

  • https://stackoverflow.com/questions/19006776/onactivityresult-not-working-with-fragments
  • o
2条回答
  •  你的背包
    2021-02-08 08:40

    i Have one Solution it is currently Working in my project. follow Step.

    --> Create Interface name OnActivityResultListener(or name as you wish).

    public interface OnActivityResultListener {

    public boolean onActivityResultTest(int request_code, int response_code,
            Intent data);
    

    }

    --> Make refrence of intercace in your FragmentActivity like

    public OnActivityResultListener activityResultListener;
    

    --> now override OnActivityResult in FragmentActivity. like below.

    @Override
    public void onActivityResult(int arg0, int arg1, Intent arg2) {
        AppLog.Log(TAG, "onActivityResult");
        try {
            if (activityResultListener != null) {
                activityResultListener.onActivityResultTest(arg0,arg1,arg2);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onActivityResult(arg0, arg1, arg2);
        }
    

    --> now implement interface in your Fragment and override required method.

    @Override
    public boolean onActivityResultTest(int requestCode, int resultCode,
            Intent data) {
        AppLog.Log(TAG, "onActivityResultTest");
        if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
            isHavePhoto = true;
            bitmap = (Bitmap) data.getExtras().get("data");
            userEditPhoto.setImageBitmap(bitmap);
        }
    }
    

    --> and the last step is inside OnAttach Method of Fragment class is register your Fragment in activity for the the Activity result. like

    @Override
        public void onAttach(Activity activity) {
            this.activity = (YOUR_FRAGMENT_ACTIVITY) activity;
                this.activity.activityResultListener = this;
            super.onAttach(activity);
        }
    

    -->now test and don't forgot to remove it

    @Override
    public void onDestroyView() {
        activity.activityResultListener = null;
        super.onDestroyView();
    }
    

    ->it is some what lengthy process but it is working 100% in any orientation.

提交回复
热议问题