简体   繁体   中英

Changing BottomNavigationView single item icon and text color

I have a BottomNavigationView:

<com.google.android.material.bottomnavigation.BottomNavigationView
        ...
        app:itemIconTint="@drawable/bottom_nav_menu_color_selector"
        app:itemTextColor="@drawable/bottom_nav_menu_color_selector"
        app:labelVisibilityMode="labeled"
        app:menu="@menu/bottom_nav_menu" />
            

with itemIconTint and itemTextColor selector:

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

and menu:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/bottomNavFirst"
        android:icon="@drawable/bottom_nav_first_selector"
        android:title="@string/bottom_nav_first_title" />

    <item
        android:id="@+id/bottomNavSecond
        android:icon="@drawable/bottom_nav_second_selector"
        android:title="@string/bottom_nav_second_title" />

</menu>

and a selector for menu item icon:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/bottom_nav_first_icon_selected" android:state_checked="true" />
    <item android:drawable="@drawable/bottom_nav_first_icon_deselected" android:state_checked="false" />
</selector>

Now depending on an application state I need to change one menu item icon color and title color. It should be grey when selected and deselected. I tried with methods setTintList or setTint with no success:

bottomNavView.menu.findItem(R.id.bottomNavFirst)?.icon?.setTintList(null)
bottomNavView.menu.findItem(R.id.bottomNavFirst)?.icon?.setTint(Color.GRAY)

Properties like iconTintList are not an option because my API level is 21. Any ideas how to achieve that?

try this to change the title color:

    SpannableString titleSpannable = new  SpannableString("title");

    titleSpannable.setSpan(
            new ForegroundColorSpan(Color.RED),
            0,
            titleSpannable.length(),
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

bottomNavView.getMenu().findItem(R.id.bottomNavFirst).setTitle(titleSpannable);

I'm looking for how to change just one icon.

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