Search code examples
javaandroidbottomnavigationviewmaterial-components-androidandroid-bottomnavigationview

Android set color of icon and text in bottomNavigationBar by program fails


I create a xml file to control my bottomNavigation bar, like this:

<?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/bottomNavigationBarCheckedNormal" />

    <item
        android:state_pressed="true"
        android:color="@color/bottomNavigationBarCheckedNormal" />

    <item
        android:color="@color/bottomNavigationBarUncheckedNormal" />
</selector>

It is works when I set this in my activity xml file, like this:

<com.google.android.material.bottomnavigation.BottomNavigationView
    android:id="@+id/activity_news_bottom_navigation"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    app:menu="@menu/bottom_navigation_menu"
    app:itemIconTint="@drawable/custom_bottom_navigation_normal"
    app:itemTextColor="@drawable/custom_bottom_navigation_normal"
    app:labelVisibilityMode="labeled" />

But I want to change this by program, so I try to use this:

bottomNavigationView.setBackgroundColor(Color.parseColor(AppColor.bottomNavigationBarBackgroundColor));
bottomNavigationView.setItemIconTintList(ColorStateList.valueOf(R.drawable.custom_bottom_navigation_normal));
bottomNavigationView.setItemTextColor(ColorStateList.valueOf(R.drawable.custom_bottom_navigation_normal));

But it is not work, icon and text color are not different when select and unselect, and the color is not I set. How can I fix it, thank you.


Solution

  • You should use:

    bottomNavigationView.setItemTextColor(
          AppCompatResources.getColorStateList(this,R.drawable.custom_bottom_navigation_normal));
    

    The method valueOf:

    Returns A ColorStateList containing a single color. This value cannot be null.