我曾经回答过一个类似的问题 这里.
基本上你需要做的是使用 Color State List Resource
。为此,首先创建一个新的 xml
文件(例如 drawer_item.xml),并将其放置在 res
目录下的 color
子目录中。如果你还没有名为 color 的文件夹,则需要创建一个。
现在,在 drawer_item.xml
中进行如下操作:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="checked state color" android:state_checked= "true" />
<item android:color="your default color" />
</selector>
对于itemBackground
,需要在drawable文件夹中放置一个单独的可绘制对象。名称相同为drawer_item
。对于itemBackground
,应设置android:drawable
属性而不是android:color
属性:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="@drawable/shape_rectangle_checked"
android:state_checked= "true" />
<item android:drawable="@drawable/shape_rectangle" />
</selector>
文件shape_rectangle
:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#ffffff" />
</shape>
文件shape_rectangle_checked
:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#25aaf1" />
</shape>
然后像这样在你的navigationview中设置
app:itemIconTint="@color/drawer_item" //notice here
app:itemTextColor="@color/drawer_item" //and here
app:itemBackground="@drawable/drawer_item"//and here for changing the background color of the item which is checked
app:itemBackground
应该是一个可绘制对象。 - Lubos Mudrak