Set toolbar title dynamically using navigation-component

后端 未结 3 472
失恋的感觉
失恋的感觉 2020-12-17 02:09

I\'m trying to set the toolbar title dynamically, I don\'t know if it\'s possible or not.

Assume I have list of items every item I clicked it\'s open new fragment,

3条回答
  •  一个人的身影
    2020-12-17 02:40

    In case you are passing a custom Object as parameter, you can use navController.addOnDestinationChangedListener.

    navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
        @Override
        public void onDestinationChanged(@NonNull NavController controller, @NonNull NavDestination destination, @Nullable Bundle arguments) {
            Log.i(TAG, "onDestinationChanged");
            switch (destination.getId()) {
                case R.id.mainFragment:
                    updateToolbarAndBottomNavigation("Main Title", "Main Subtitle", View.VISIBLE);
                    break;
                case R.id.shopFragment:
                    updateToolbarAndBottomNavigation("custom title", null, View.VISIBLE);
                    break;
                case R.id.shopcartFragment:
                    StoreEntity store = (StoreEntity) arguments.get("storeEntity");
                    Log.i(TAG, "onDestinationChanged: ShopCartFragment args: "+store.getName());
                    updateToolbarAndBottomNavigation(store.getName(), null, View.GONE);
                    break;
            }
    
        }
    });
    
    private void updateToolbarAndBottomNavigation(String title, String subtitle, int visibility) {
        getSupportActionBar().setTitle(title);
        getSupportActionBar().setSubtitle(subtitle);
        bottomNavigationView.setVisibility(visibility);
    }
    

    Where the arguments.get() was retrieved from android:name in the nav_graph.xml.

    
            
        
    

    I hope it can help more people!

提交回复
热议问题