2

I am using the default BottomView Navigation bar for my application which has 4 buttons and they have an awful shifting animation, and there doesn't seem to be a method in the compat lib. to disable it. Please help.

P.s I don't want to use third party bottom navs.

SurvivalMachine
  • 7,946
  • 15
  • 57
  • 87
Anubhav Malik
  • 242
  • 7
  • 13

1 Answers1

1
//Create a new class Bottom Navigation Bar helper and then implement it in the buttons classes

public class BottomNavigationViewHelper {
    @SuppressLint("RestrictedApi")
    public static void disableShiftMode(BottomNavigationView view) {
        BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0);
        try {
            Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode");
            shiftingMode.setAccessible(true);
            shiftingMode.setBoolean(menuView, false);
            shiftingMode.setAccessible(false);
            for (int i = 0; i < menuView.getChildCount(); i++) {
                BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i);
                //noinspection RestrictedApi
                item.setShiftingMode(false);
                // set once again checked value, so view will be updated
                //noinspection RestrictedApi
                item.setChecked(item.getItemData().isChecked());
            }
        } catch (NoSuchFieldException e) {
            Log.e("BNVHelper", "Unable to get shift mode field", e);
        } catch (IllegalAccessException e) {
            Log.e("BNVHelper", "Unable to change value of shift mode", e);
        }
    }


//and then just use this code in every button class

 protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_activity);
        BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavViewBar);
        BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
        BottomNavigationViewHelper.enableNavigation(mContext, bottomNavigationView);
        Menu menu=bottomNavigationView.getMenu();
        MenuItem menuItem=menu.getItem(ACTIVITY_NUM);
        menuItem.setChecked(true);
    }

This will make the buttons perform nicely. I am new to android, the code is not written by me but I hope it helps you

Dan Oprean
  • 56
  • 7
  • Check this if you use API version >= 28 https://stackoverflow.com/a/52736226/5597765. Basically, they've removed the mShiftingMode variable from BottomNavigationBar so we have to hack it differently. – Harvey Mar 19 '19 at 07:21