Get fragment from NavController
Can't say the code snippet (I've added below) is the best solution, but it worked for me to get the recent/current fragment added in NavHostFragment
used in Android Navigation Component's implementations
OR
You can even override onActivityResult
of the you activity with your fragment's, all you need is to get the added Fragment
and call it's onActivityResult
, using this code snippet:
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
Fragment fragment = navHostFragment.getChildFragmentManager().getFragments().get(0);
fragment.onActivityResult(requestCode, resultCode, data);
Patrick
I’m an iOS/Android software engineer who thrives on creating apps with optimal user experiences. With a background in human-computer interaction, I specialize in a esthetically pleasing interfaces that are intuitive, seamless, and functional.
Updated on June 04, 2022Comments
-
Patrick almost 2 years
I have one NavController (navOrdersController) with 2 fragments inside. My current fragment is OrderDetailFragment and I want access to first Fragment (OrdersFragment) to update data in MainActivity. How can I do this?
I tried findFragmentByTag and findFragmentByID but always return null.
I got access OrderDetailFragment with:
this.supportFragmentManager.fragments[position].findNavController().currentDestination
But I need previous fragment. Thank you very much
-
Patrick over 5 yearsThanks Rahul. It doesn't work because parent is an NavGraph, and child is OrderDetailFragment. OrdersFragment is in the middle
-
Rahul Sharma over 5 yearsNavGraph should not be a parent. Because the parent can be
Activity
orFragment
. I am not sure though. Give me a few minutes to check. -
Patrick over 5 yearsIt doesn´t work. "null cannot be cast to non-null type android.navigation.fragment.NavHostFragment" because parent is null. I updated my question. I have to work with navController
-
Rahul Sharma over 5 yearshere zero is the backstack index (which should have been in case you were implementing the graph yourself)
-
Patrick over 5 yearsThanks Rahul but still not working, parent is null. Fragments are inside NavController