Android通过程序在bottomNavigationBar中设置图标和文本的颜色失败

问题描述

我创建一个xml文件来控制我的bottomNavigation栏,如下所示:

<?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>

当我在活动xml文件中进行设置时,它是可行的,如下所示:

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

但是我想通过程序更改它,所以我尝试使用它:

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

但是它不起作用,选择和取消选择时图标和文本的颜色没有区别,并且颜色不是我设置的。谢谢,我该如何解决

解决方法

您应该使用:

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

方法valueOf

返回包含单一颜色的ColorStateList。此值不能为空。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...