2017-08-28 129 views
0

是否可以更改每個選項卡的狀態檢查顏色? 我可以通過將選擇器添加到BottomNavigation來更改BottomNavigationstate_checked的顏色。Android - 更改`BottomNavigationView`` state_checked`顏色

我需要的是在每個選項卡上更改state_checked顏色。 ie; 如果我點擊第一個圖標我BottomNavigation我需要的圖標state_checked改變顏色爲綠色,在第二個圖標改變顏色爲紅色等。

BottomNavigationView

<android.support.design.widget.BottomNavigationView 
    android:id="@+id/navigation" 
    android:layout_width="match_parent" 
    android:layout_height="120dp" 
    android:layout_gravity="bottom" 
    app:itemIconTint="@drawable/selector" 
    app:itemTextColor="@drawable/selector" 
    android:background="?android:attr/windowBackground" 
    app:menu="@menu/navigation" /> 

selector.xml

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
<item android:state_checked="true" android:color="@color/green" /> 
<item android:color="@android:color/darker_gray" /> 
</selector> 

現在state_checked顏色爲綠色,默認顏色爲灰色。

回答

0

您可以動態地這樣做,因爲 -

public static StateListDrawable selectorForColor (int normalColor,int pressedColor) { 
     StateListDrawable states = new StateListDrawable(); 
     states.addState (new int[]{ android.R.attr.state_pressed }, 
      new ColorDrawable(pressed)); 
     states.addState (new int[]{ }, new ColorDrawable(normal)); 
     return states; 
    } 

打電話給你BottomNavigation項目onClick()這裏面的方法,並傳遞要爲這個項目設置顏色。您可以創建array的顏色,該顏色在BottomNavigation的每個index處具有該項目的顏色。 此方法將return a drawable對象,您可以將其設置爲您的項目view