Set selected item in Android BottomNavigationView

前端 未结 21 2310
谎友^
谎友^ 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:46

    I hope this helps

    //Setting default selected menu item and fragment
            bottomNavigationView.setSelectedItemId(R.id.action_home);
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fragment_container, new HomeFragment()).commit();
    

    It is more of determining the default fragment loaded at the same time with the corresponding bottom navigation menu item. You can include the same in your OnResume callbacks

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

    Use this to set selected bottom navigation menu item by menu id

    MenuItem item = mBottomNavView.getMenu().findItem(menu_id);
    item.setChecked(true);
    
    0 讨论(0)
  • 2020-11-27 14:51

    To programmatically click on the BottomNavigationBar item you need use:

    View view = bottomNavigationView.findViewById(R.id.menu_action_item);
    view.performClick();
    

    This arranges all the items with their labels correctly.

    0 讨论(0)
  • 2020-11-27 14:53
    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
    
       bottomNavigationView.setOnNavigationItemSelectedListener(this);
       Menu menu = bottomNavigationView.getMenu();
       this.onNavigationItemSelected(menu.findItem(R.id.action_favorites));
    }
    
    0 讨论(0)
  • 2020-11-27 14:53

    You can try the performClick method :

    View view = bottomNavigationView.findViewById(R.id.YOUR_ACTION);
    view.performClick();
    

    Edit

    From API 25.3.0 it was introduced the method setSelectedItemId(int id) which lets you mark an item as selected as if it was tapped.

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

    This method work for me.

    private fun selectBottomNavigationViewMenuItem(bottomNavigationView : BottomNavigationView,@IdRes menuItemId: Int) {
                bottomNavigationView.setOnNavigationItemSelectedListener(null)
                bottomNavigationView.selectedItemId = menuItemId
                bottomNavigationView.setOnNavigationItemSelectedListener(this)
            }
    

    Example

     override fun onBackPressed() {
            replaceFragment(HomeFragment())
            selectBottomNavigationViewMenuItem(navView, R.id.navigation_home)
        }
    
    
    
    private fun replaceFragment(fragment: Fragment) {
            val transaction: FragmentTransaction = supportFragmentManager.beginTransaction()
            transaction.replace(R.id.frame_container, fragment)
            transaction.commit()
        }
    
    0 讨论(0)
提交回复
热议问题