How to dynamically hide a menu item in BottomNavigationView?

后端 未结 9 1547
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-30 20:04

I want to hide a menu item of BottomNavigationView dynamically based on some conditions. I tried the following but it is not working.

mBottomNavigationView.g         


        
9条回答
  •  独厮守ぢ
    2020-12-30 20:38

    In my case, I wanted to hide the toolbar text and the icons/titles of BottomNavigationView items in the authorization fragment, which handles the initial loading of my application. When it determines that the user is authenticated and fetches their profile from the database, I load the feed fragment, which fetches data from the database and displays it to the user. What I did was add the following method to the activity that creates the layout elements and call it from its fragments, passing in a boolean to determine visibility of the items.

    public void setBottomNavigationViewItemsVisibility(boolean value) {
        if (this.bottomNavigationView != null) {
            this.bottomNavigationView.setVisibility(View.VISIBLE);
            Menu menu = this.bottomNavigationView.getMenu();
            if (value) {
                int[] icons = {R.drawable.ic_event_white_24dp, R.drawable.ic_explore,
                        R.drawable.ic_store_white_24dp, R.drawable.ic_notifications_white_24dp};
                int[] titles = {R.string.feed, R.string.explore, R.string.finder, R.string.notifications};
                for (int i = 0; i < menu.size(); i++) {
                    menu.getItem(i).setIcon(icons[i]);
                    menu.getItem(i).setTitle(titles[i]);
                    menu.getItem(i).setEnabled(true);
                }
            } else {
                for (int i = 0; i < menu.size(); i++) {
                    menu.getItem(i).setIcon(R.drawable.ic_empty);
                    menu.getItem(i).setTitle(R.string.title_empty);
                    menu.getItem(i).setEnabled(false);
                }
            }
        }
    }
    

    We declare an array of drawable ids and an array of title ids to match what we have declared in the menu XML file. If true, we iterate through the menu items and set their icon, title, and their state to default values. If false, we set the icon to a transparent icon (removing the icon affects its size), set the toolbar title to an empty string, and disable it.

    BottomNavigationView Menu:

    
    
    
        
        
        
        
    
    

    Empty Icon (ic_empty.xml):

    
        
    
    

    Empty Title (title_empty):

    
    

提交回复
热议问题