【问题标题】:Color state list "event" not triggered or handled颜色状态列表“事件”未触发或处理
【发布时间】:2018-11-05 05:39:10
【问题描述】:

我关注了这个答案:NavigationView theme selected item background style 和这个答案:Android - Navigation View item menu background color

考虑一下这个导航视图。它使用颜色状态列表color_state_menu

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

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

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

【问题讨论】:

  • 你是否也尝试过像这样的state_checked
  • 是的,我也试过了
  • 当我点击一个菜单项时,相应的片段被加载并且点击的菜单项的背景没有改变。

标签: android android-navigationview


【解决方案1】:

你需要做几件事:

  1. 使用DrawableStateList 而不是ColorStateList - 只需将color_state_menu.xml 移动到drawable 文件夹并更改

    app:itemBackground="@color/color_state_menu"
    

    app:itemBackground="@drawable/color_state_menu"
    
  2. 使用android:state_checked 代替android:state_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>
    
  3. android:checkable="true"添加到drawer_view.xml中的每个菜单项

【讨论】:

  • 我没想过要检查这些项目。因此,我只是尝试在导航视图OnItemClickListener 处理程序中调用setCheckable(true),之后我一直调用setChecked(true) 并且它有效!谢谢!注意color_state_menu.xml 可以同时保存到res/colorres/drawable 目录中(没关系)。最后,state_checked 似乎确实是好的状态(我没有尝试使用state_activated)。
猜你喜欢
  • 1970-01-01
  • 2022-01-08
  • 1970-01-01
  • 2011-04-25
  • 2012-04-15
  • 2011-09-07
  • 1970-01-01
  • 1970-01-01
  • 2012-10-21
相关资源
最近更新 更多