Set selected item in Android BottomNavigationView

前端 未结 21 2311
谎友^
谎友^ 2020-11-27 14:16

I am using the new android.support.design.widget.BottomNavigationView from the support library. How can I set the current selection from code? I realized, that

相关标签:
21条回答
  • 2020-11-27 14:54
    bottomNavigationView.setSelectedItemId(R.id.action_item1);
    

    where action_item1 is menu item ID.

    0 讨论(0)
  • 2020-11-27 14:56

    use

            bottomNavigationView.getMenu().getItem(0).setChecked(true);
    
    0 讨论(0)
  • 2020-11-27 14:58

    Just adding another way to perform a selection programatically - this is probably what was the intention in the first place or maybe this was added later on.

    Menu bottomNavigationMenu = myBottomNavigationMenu.getMenu();
    bottomNavigationMenu.performIdentifierAction(selected_menu_item_id, 0);
    

    The performIdentifierAction takes a Menu item id and a flag.

    See the documentation for more info.

    0 讨论(0)
  • 2020-11-27 14:58

    Seems to be fixed in SupportLibrary 25.1.0 :) Edit: It seems to be fixed, that the state of the selection is saved, when rotating the screen.

    0 讨论(0)
  • 2020-11-27 14:58

    Reflection is bad idea.

    Head to this gist. There is a method that performs the selection but also invokes the callback:

      @CallSuper
        public void setSelectedItem(int position) {
            if (position >= getMenu().size() || position < 0) return;
    
            View menuItemView = getMenuItemView(position);
            if (menuItemView == null) return;
            MenuItemImpl itemData = ((MenuView.ItemView) menuItemView).getItemData();
    
    
            itemData.setChecked(true);
    
            boolean previousHapticFeedbackEnabled = menuItemView.isHapticFeedbackEnabled();
            menuItemView.setSoundEffectsEnabled(false);
            menuItemView.setHapticFeedbackEnabled(false); //avoid hearing click sounds, disable haptic and restore settings later of that view
            menuItemView.performClick();
            menuItemView.setHapticFeedbackEnabled(previousHapticFeedbackEnabled);
            menuItemView.setSoundEffectsEnabled(true);
    
    
            mLastSelection = position;
    
        }
    
    0 讨论(0)
  • 2020-11-27 15:01

    Above API 25 you can use setSelectedItemId(menu_item_id) but under API 25 you must do differently, user Menu to get handle and then setChecked to Checked specific item

    0 讨论(0)
提交回复
热议问题