onActivityResult is not being called in Fragment

后端 未结 30 2630
忘了有多久
忘了有多久 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:53

    With Android's Navigation component, this problem, when you have nested Fragments, could feel like an unsolvable mystery.

    Based on knowledge and inspiration from the following answers in this post, I managed to make up a simple solution that works:

    • Answer in this post
    • Answer in this post

    In your activity's onActivityResult(), you can loop through the active Fragments list that you get using the FragmentManager's getFragments() method.

    Please note that for you to do this, you need to be using the getSupportFragmentManager() or targeting API 26 and above.

    The idea here is to loop through the list checking the instance type of each Fragment in the list, using instanceof.

    While looping through this list of type Fragment is ideal, unfortunately, when you're using the Android Navigation Component, the list will only have one item, i.e. NavHostFragment.

    So now what? We need to get Fragments known to the NavHostFragment. NavHostFragment in itself is a Fragment. So using getChildFragmentManager().getFragments(), we once again get a List of Fragments known to our NavHostFragment. We loop through that list checking the instanceof each Fragment.

    Once we find our Fragment of interest in the list, we call its onActivityResult(), passing to it all the parameters that the Activity's onActivityResult() declares.

    //  Your activity's onActivityResult()
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
    
            List lsActiveFragments = getSupportFragmentManager().getFragments();
            for (Fragment fragmentActive : lsActiveFragments) {
    
                if (fragmentActive instanceof NavHostFragment) {
    
                    List lsActiveSubFragments = fragmentActive.getChildFragmentManager().getFragments();
                    for (Fragment fragmentActiveSub : lsActiveSubFragments) {
    
                        if (fragmentActiveSub instanceof FragWeAreInterestedIn) {
                            fragmentActiveSub.onActivityResult(requestCode, resultCode, data);
                        }
    
                    }
    
                }
    
            }
    
        }

提交回复
热议问题