Disable BottomNavigationView shift mode?
Implementation of
BottomNavigationView
has condition: when there is more than 3 items then use shift mode.
At this moment you cannot change it through existing API and the only way to disable shift mode is to use reflection.
You’ll need helper class:
import android.support.design.internal.BottomNavigationItemView;
import android.support.design.internal.BottomNavigationMenuView;
import android.support.design.widget.BottomNavigationView;
import android.util.Log;
import java.lang.reflect.Field;
public class BottomNavigationViewHelper {
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 apply
disableShiftMode
method on your BottomNavigationView
, but remember if you are inflating menu view from your code, you have to execute it after inflating.
Example usage:
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation_bar);
BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
PS.
Remember, you’ll need to execute this method each time you change menu items in your
BottomNavigationView
.
UPDATE
You also need to update proguard configuration file (e.g. proguard-rules.pro), code above uses reflection and won’t work if proguard obfuscate the
mShiftingMode
field.-keepclassmembers class android.support.design.internal.BottomNavigationMenuView {
boolean mShiftingMode;
}
Advertisements
Comments
Post a Comment