onActivityResult is not being called in Fragment

后端 未结 30 2635
忘了有多久
忘了有多久 2020-11-21 04:28

The activity hosting this fragment has its onActivityResult called when the camera activity returns.

My fragment starts an activity for a result with th

30条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-21 04:52

    Your code has a nested fragment. Calling super.onActivityForResult doesn't work

    You don't want to modify every activity that your fragment can be called from and or make a work around calling every fragment in the fragment chain.

    Here is one of many working solutions. create a fragment on the fly and wire it directly to the activity with the support fragment manager. Then call startActivityForResult from the newly created fragment.

    private void get_UserEmail() {
    
        if (view == null) {
            return;
        }
        ((TextView) view.findViewById(R.id.tvApplicationUserName))
                .setText("Searching device for user accounts...");
    
        final FragmentManager fragManager = getActivity().getSupportFragmentManager();
    
        Fragment f = new Fragment() {
            @Override
            public void onAttach(Activity activity) {
                super.onAttach(activity);
                startActivityForResult(AccountPicker.newChooseAccountIntent(null, null,
                        new String[]{"com.google"}, false, null, null, null, null), REQUEST_CODE_PICK_ACCOUNT);
            }
    
            @Override
            public void onActivityResult(int requestCode, int resultCode,
                                         Intent data) {
                if (requestCode == REQUEST_CODE_PICK_ACCOUNT) {
                    String mEmail = "";
                    if (resultCode == Activity.RESULT_OK) {
                        if (data.hasExtra(AccountManager.KEY_ACCOUNT_NAME)) {
                            mEmail = data
                                    .getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
                        }
                    }
                    if (mActivity != null) {
                        GoPreferences.putString(mActivity, SettingApplication.USER_EMAIL, mEmail);
                    }
                    doUser();
                }
                super.onActivityResult(requestCode, resultCode, data);
                fragManager.beginTransaction().remove(this).commit();
            }
        };
        FragmentTransaction fragmentTransaction = fragManager
                .beginTransaction();
        fragmentTransaction.add(f, "xx" + REQUEST_CODE_PICK_ACCOUNT);
        fragmentTransaction.commit();
    }
    

提交回复
热议问题