说明:BottomNavigationView默认的item数量是3-5个。如果超过5个会报错;如果超过3个,底部按钮的位置会滑动,不固定。
如何实现固定呢,目前只能通过反射的方式改变源码中参数(mShifingMode为false),按钮位置就会固定。
反射类:
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);
}
}
}
使用:
private void initView(){
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);//id是布局文件中的BottomNavigationView中的id
BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
}