【问题标题】:Selected ListView item doesn't change text color even with ColorStateList resource assigned即使分配了 ColorStateList 资源,选定的 ListView 项目也不会更改文本颜色
【发布时间】:2018-02-12 23:43:27
【问题描述】:

我希望 ListView 中项目的文本颜色在被选中时发生变化。我阅读了以下帖子(How to set ListView selected item alternet text color in android)并进行了以下更改:

创建了一个 ColorStateList 资源@drawable/list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#ffffff00" /> <!-- default -->
<item
    android:state_pressed="true"
    android:color="#ff000000" />
<item
    android:state_selected="true"
    android:color="#ffff0000" />
<item
    android:state_focused="true"
    android:color="#ff0000ff" />

将资源分配给目标TextView中的textColor属性

<TextView
    android:id="@+id/person_active_list_name"
    android:paddingLeft="@dimen/person_list_name_left_padding"
    android:layout_width="wrap_content"
    android:layout_height="@dimen/person_list_image_size"
    android:layout_toEndOf="@id/person_active_thumbnail"
    android:layout_toLeftOf="@id/person_active_list_arrow"
    android:layout_toRightOf="@id/person_active_thumbnail"
    android:layout_toStartOf="@id/person_active_list_arrow"
    android:gravity="center|start"
    android:textColor="@drawable/list_item" />

由于某种原因,仅应用了 @drawable/list_item.xml 中的默认颜色(因此 ColorStateList 资源确实被 TextView 消耗)。但是,当按下、选择列表项等时,文本颜色没有变化。感谢任何帮助!

【问题讨论】:

    标签: android listview


    【解决方案1】:

    来自文档:

    注意:请记住,状态列表中与对象当前状态匹配的第一项将被应用。因此,如果列表中的第一项不包含上述任何状态属性,则每次都会应用它,这就是为什么您的默认值应始终为 last

    因此,请将您的定义改为:

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    
        <item
            android:state_pressed="true"
            android:color="#ff000000" />
    
        <item
            android:state_selected="true"
            android:color="#ffff0000" />
    
        <item
            android:state_focused="true"
            android:color="#ff0000ff" />
    
        <item android:color="#ffffff00" /> <!-- default -->
    
    </selector>
    

    【讨论】:

    • 啊,感谢您向我指出这一点!我只是没有阅读完整的文档,我很傻。它现在正在工作,非常感谢。此外,对于遇到这种情况的其他人,我的特殊情况需要使用 state_activated="true" 而不是 state_selected="true"。
    猜你喜欢
    • 2012-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-06
    • 1970-01-01
    • 1970-01-01
    • 2012-10-10
    • 1970-01-01
    相关资源
    最近更新 更多