简体   繁体   中英

Android - Change `BottomNavigationView` `state_checked` color

is it possible to change state checked color for each tab? i am able to change the BottomNavigation state_checked color by adding the selector to BottomNavigation .

what i need is to change the state_checked color on each tab. ie; if i click the first icon on my BottomNavigation i need to change the icon state_checked color to green, on second icon change color to red etc..

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>

now the state_checked color is Green and default color is gray.

You can do this dynamically as -

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;
    }

Call this method inside your onClick() of BottomNavigation item and pass the colors you want to set for this item. You can create an array of colors which will have colors for the item at each index of BottomNavigation . This method will return a drawable object which you can set to your item view .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM