The activity hosting this fragment has its onActivityResult
called when the camera activity returns.
My fragment starts an activity for a result with th
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
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);
}
}
}
}
}