Android “颜色状态列表”;事件“;未触发或处理的

Android “颜色状态列表”;事件“;未触发或处理的,android,android-navigationview,Android,Android Navigationview,我遵循这个答案:还有这个: 考虑这个导航视图。它使用颜色状态列表color\u state\u菜单 <android.support.design.widget.NavigationView app:itemBackground="@color/color_state_menu" android:id="@+id/navigation_view" android:layout_width="wrap_content" android:layout_heigh

我遵循这个答案:还有这个:

考虑这个导航视图。它使用颜色状态列表
color\u state\u菜单

<android.support.design.widget.NavigationView
    app:itemBackground="@color/color_state_menu"
    android:id="@+id/navigation_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:menu="@menu/drawer_view">

此颜色状态列表定义如下:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_activated="true" android:drawable="@color/colorRoyalRed" />
    <item android:drawable="@color/gray" />
</selector>

。。。这样,当前使用的菜单项具有红色背景,而其他菜单项具有灰色背景


但是,所有这些菜单项始终具有灰色背景。你知道为什么吗?

你需要做几件事:

  • 使用
    DrawableStateList
    而不是
    ColorStateList
    -只需将
    color\u state\u menu.xml
    移动到
    drawable
    文件夹并更改

    app:itemBackground="@color/color_state_menu"
    

  • 使用
    android:state\u checked
    而不是
    android:state\u activated

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@color/colorRoyalRed" android:state_checked="true" />
        <item android:drawable="@color/gray" />
    </selector>
    
    
    
  • android:checkable=“true”
    添加到
    drawer\u view.xml中的每个菜单项


  • 您是否也尝试过这样的
    state_checked
    ?是的,我也尝试过当我单击一个菜单项时,加载相应的片段,并且单击的菜单项的背景没有改变。我不认为这些项目是可检查的。因此,在我保持对
    setChecked(true)
    的调用之后,我尝试在导航视图
    OnItemClickListener
    处理程序中调用
    setChecked(true)
    ,它就工作了!非常感谢。请注意,
    color\u state\u menu.xml
    可以保存到
    res/color
    res/drawable
    目录中(这无关紧要)。最后,
    state\u checked
    似乎确实是一个好状态(我没有尝试激活
    state\u
    )。
    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@color/colorRoyalRed" android:state_checked="true" />
        <item android:drawable="@color/gray" />
    </selector>