1. 程式人生 > >Android利用系統原生BottomNavigationView實現底部導航

Android利用系統原生BottomNavigationView實現底部導航

rnorm .get nbsp upd access help value getitem span

   <android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:background="#2488e2"
  app:itemIconTint
="@color/tab_icon" app:itemTextColor="@color/tab_icon" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:menu="@menu/navigation" />
itemIconTint,
itemTextColor:分別代表選中和非選中狀態下按鈕圖標和文字的顏色

在color下新建tab_icon.xml,
<selector xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:color="@color/colorNormal" android:state_checked="false" />
    <item android:color="@color/colorSelected" android:state_checked="true"/>
</selector>

menu:在menu下建一個xxmenu.xml ,每一個item代表一個底部標簽

 <
item android:id="@+id/navigation_1" android:icon="@drawable/icon" android:title="@string/tab_title" />

當底部item過多的時候點擊會有一個偏移的現象????

解決方法:定義一個工具類
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) {

        } catch (IllegalAccessException e) {

        }
    }

}



Android利用系統原生BottomNavigationView實現底部導航