Search code examples
androidandroid-layoutbottomnavigationviewandroid-bottomnav

Can I disable shifting in specific BottomNavigationView item on specific logic?


Currently I have an implementation like this-

    mBottomNav.setOnNavigationItemSelectedListener(
                ......
     switch (item.getItemId()) {

       case R.id.actionUser:
          if(userLoggedIn) {
              mHomePresenter.btnUser();
          }
          else {
              showLongToast("User Not Logged In");
          }
          break;
    });

The logical else part where I will show the toast message, neither I want the BottomNavigationView to shift nor the change of menu icon colour.

How I can implement such logic only on this specific part? All the other menu item will persist the default shifting logic.


Solution

  • Well the answer is quite simple, for the condition you want the transition to happen, return true for the condition where you dont want return false

    Taking your code into account, it should be

    mBottomNav.setOnNavigationItemSelectedListener(
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
          switch (item.getItemId()) {
            case R.id.actionUser:
                if(userLoggedIn) {
                    mHomePresenter.btnUser();
                    return true;
                }
                else {
                    showLongToast("User Not Logged In");
                    return false;
                }
            }
        });
    

    if you check the documentation for the Navigation selection listener, you can see

    /**
     * Listener for handling selection events on bottom navigation items.
     */
    public interface OnNavigationItemSelectedListener {
    
        /**
         * Called when an item in the bottom navigation menu is selected.
         *
         * @param item The selected item
         *
         * @return true to display the item as the selected item and false if the item should not
         *         be selected. Consider setting non-selectable items as disabled preemptively to
         *         make them appear non-interactive.
         */
        boolean onNavigationItemSelected(@NonNull MenuItem item);
    }