Search code examples
androidandroid-fragmentsandroid-jetpackandroid-architecture-componentsandroid-architecture-navigation

Can I change topLevelDestinationIds from AppBarConfiguration?


I have CountriesFragment and this fragment is launching first (start destination)

I hide the back button using this code

NavigationUI.setupWithNavController(materialtoolbar, navController, new AppBarConfiguration.Builder(
                R.id.navigationMain_fragment_countriesFragment).build());

The user can change the country also by going to SettingsFragment and inside this SettingsFragment there is a button called Change The Country, After clicking on it will navigate the user to CountriesFragment.

I want to show the back button in CountriesFragment if the user coming from SettingsFragment, Otherwise hide it.

The problem is the back button is still hidden in all cases

Is it possible to modify topLevelDestinationIds in AppBarConfiguration or any better solution?


Solution

  • This trick solved the problem

    private boolean isToolbarLinkedWithNavigationUI;
    
    @Override
    public void onDestinationChanged(@NonNull NavController navController, @NonNull NavDestination navDestination, @Nullable Bundle bundle) {
        if (navDestination.getId() == R.id.navigationMain_homeFragment && !isToolbarLinkedWithNavigationUI) {
            isToolbarLinkedWithNavigationUI = true;
            NavigationUI.setupWithNavController(activityMainBinding.toolbar, navController, new AppBarConfiguration.Builder(
                R.id.navigationMain_homeFragment
            ).setOpenableLayout(activityMainBinding.getRoot()).build());
        }
    
    ...
    
    }
    

    Previously, I was setup NavigationUI inside CountriesFragment, but now setup NavigationUI inside HomeFragment.