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:
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<Fragment>
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()_x000D_
_x000D_
@Override_x000D_
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {_x000D_
super.onActivityResult(requestCode, resultCode, data);_x000D_
_x000D_
List<Fragment> lsActiveFragments = getSupportFragmentManager().getFragments();_x000D_
for (Fragment fragmentActive : lsActiveFragments) {_x000D_
_x000D_
if (fragmentActive instanceof NavHostFragment) {_x000D_
_x000D_
List<Fragment> lsActiveSubFragments = fragmentActive.getChildFragmentManager().getFragments();_x000D_
for (Fragment fragmentActiveSub : lsActiveSubFragments) {_x000D_
_x000D_
if (fragmentActiveSub instanceof FragWeAreInterestedIn) {_x000D_
fragmentActiveSub.onActivityResult(requestCode, resultCode, data);_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
}
_x000D_