Get fragment from NavController

10,583

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);
Share:
10,583
Patrick
Author by

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, 2022

Comments

  • Patrick
    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?

    enter image description here

    I tried findFragmentByTag and findFragmentByID but always return null.

    I got access OrderDetailFragment with:

    this.supportFragmentManager.fragments[position].findNavController().currentDestination
    

    enter image description here

    But I need previous fragment. Thank you very much

  • Patrick
    Patrick over 5 years
    Thanks Rahul. It doesn't work because parent is an NavGraph, and child is OrderDetailFragment. OrdersFragment is in the middle
  • Rahul Sharma
    Rahul Sharma over 5 years
    NavGraph should not be a parent. Because the parent can be Activity or Fragment. I am not sure though. Give me a few minutes to check.
  • Patrick
    Patrick over 5 years
    It 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
    Rahul Sharma over 5 years
    here zero is the backstack index (which should have been in case you were implementing the graph yourself)
  • Patrick
    Patrick over 5 years
    Thanks Rahul but still not working, parent is null. Fragments are inside NavController