Search code examples
androidandroid-fragmentsfragment-backstack

Is there a way to load a fragment from the back stack using the Navigation Component?


I have a number of custom tabs, and I want the NavController to load a fragment from the back stack if it exists when the user navigates between tabs.

I check if a fragment exists in my back stack, and if it doesn't, I navigate to it. However, how can I load a fragment from the back stack when it already exists there?

try {  //check if fragment exists in back stack
    navController.getBackStackEntry(R.id.myFragment);

    // what should I do here?
} catch (Exception e) {
    navController.navigate(R.id.action_to_myFragment);
}

Solution

  • If you want to access the fragment on the backstack, you can use the code below.

    findNavController().popBackStack(R.id.myFragment, false)
    
    // argument false : inclusivity settings