When using the Navigation component, it is simple to navigate to the next fragment and also simple to pop back to the previous fragment.
Navigation.findNavController(v).navigate(R.id.action1);
/*vs*/
Navigation.findNavController(v).popBackStack();
How can I check within onViewCreated()
how startDestination / topLevel destination fragments were reached? If it was poped back to I want to run different code compared to when it was newly navigated to.
Update thanks to @Thracian for the suggestions:
I tested:
navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
@Override
public void onDestinationChanged(@NonNull NavController controller, @NonNull NavDestination destination, @Nullable Bundle arguments) {
Log.d("MAIN", "New destination ID: " + destination.getDisplayName());
}
});
But it returns the same result, whether I directly navigate to a fragment or use popBack/navigateUp, so it does not help to distinguish.
I tested:
navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
navHostManager = navHostFragment.getChildFragmentManager();
navHostManager.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
int backStackEntryCount = navHostManager.getBackStackEntryCount();
int fragmentCount = navHostManager.getFragments().size();
Log.e("MAIN","backStackEntryCount: "+backStackEntryCount+", fragmentCount: " + fragmentCount);
}
});
Unfortunately the fragment I try to solve this for is the startDestination. Hence the backStackEntryCount
is always 0 when I reach it, both for navigateTo and for navigateUp ...
For my other top-level destinations this does also not properly work, as they always show backStackEntryCount = 1
independent of how I reach them.
from Navigation component - how to check whether the fragment is newly navigated to vs. poped back to
No comments:
Post a Comment