简体   繁体   English

Android ListView行背景色

[英]Android ListView row background color

I have looked at numerous SO questions and cannot figure this out. 我已经看过很多SO问题,无法解决。 I have managed to use a selector to change the hilighting color of my ListView -but how do I set the normal (non-pressed) background colour? 我设法使用选择器更改了ListView的亮色-但是如何设置常规(非按下)背景色?

The below XML doesn't work as is only changes my row item background to black once the item has been pressed. 下面的XML无效,因为一旦按下该行,它只会将我的行项目背景更改为黑色。 How should I be doing this? 我应该怎么做?

<selector xmlns:android="http://schemas.android.com/apk/res/android"
    android:exitFadeDuration="@android:integer/config_mediumAnimTime">
    <item android:state_focused="true" android:drawable="@color/row_hilight"/>
    <item android:state_pressed="true" android:drawable="@color/row_hilight"/>
    <item android:state_pressed="false" android:drawable="@color/black"/>
</selector>

Just add one more item at the end: 只需在末尾再添加一个项目:

    <item android:drawable="@color/default_color"/>

From the documentation for state list drawables : 状态列表可绘制文档中:

During each state change, the state list is traversed top to bottom and the first item that matches the current state is used—the selection is not based on the "best match," but simply the first item that meets the minimum criteria of the state. 在每次状态更改期间,都会从上到下遍历状态列表,并使用与当前状态匹配的第一项-选择不是基于“最佳匹配”,而是仅满足该状态的最低标准的第一项。

Therefore, having an item with no specific criteria will match if none of the others do. 因此,如果没有其他特定条件的项目没有其他标准,则将匹配该项目。

You need to have a default state which does not have state. 您需要具有一个没有状态的默认状态。

Also you need to remove android:state_pressed="false" that is because it has the same functionality with the default state. 另外,您还需要删除android:state_pressed="false" ,因为它具有与默认状态相同的功能。

<selector xmlns:android="http://schemas.android.com/apk/res/android"
    android:exitFadeDuration="@android:integer/config_mediumAnimTime">
    <item android:state_focused="true" android:drawable="@color/row_hilight"/>
    <item android:state_pressed="true" android:drawable="@color/row_hilight"/>
    <item android:state_pressed="false" android:drawable="@color/black"/> //delete this
    <item android:drawable="@color/black"/> //add this
</selector>

make a custom listview with a custom adapter: 使用自定义适配器创建自定义列表视图:

Custom Adapter for List View 列表视图的自定义适配器

this was you can use a view with the background you want in getView 这是您可以在getView中使用所需背景的视图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM