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

102 Views Asked by At

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);
}
2

There are 2 best solutions below

2
ΓDΛ On BEST ANSWER

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
1
Hezy Ziv On

try popBackStack:

try {
  
    NavBackStackEntry entry = navController.getBackStackEntry(R.id.myFragment);

    if (entry != null) {
        // Pop fragments from the back stack 
        navController.popBackStack(entry.getDestination().getId(), false);
    } else {
      
        navController.navigate(R.id.action_to_myFragment);
    }
} catch (Exception e) {
    // Handle exceptions if necessary
}