在 Android 上更改 ListView 项目的背景颜色

在 Android 上更改 ListView 项目的背景颜色

问题描述:

如何在每个项目的基础上更改 ListView 项目的背景颜色.当我在 ListView 项目布局中使用 android:backgroundColor 时,我可以实现这一点,但是列表选择器不再可见.我可以通过将 drawSelectorOnTop 设置为 true 来使选择器再次可见,但随后选择器会覆盖整个项目.

How can I change background color of ListView items on a per-item basis. When I use android:backgroundColor in the ListView item layout I can achieve this, however the list selector is no longer visible. I can make the selector visible again by setting drawSelectorOnTop to true but then the selector overlays the whole item.

任何想法如何更改这些背景颜色并保留选择器?

Any ideas how to change those background colors and keep the selector?

PS 我宁愿不改变选择器本身.

PS I would rather not change the selector itself.

GMail 应用程序的作者已经设法实现了这一点,所以这绝对是可能的.

Authors of GMail application have managed to achieve exactly this so it's definitely possible.

您必须为要使用的每种颜色创建不同的状态可绘制对象.

You have to create a different state drawable for each color you want to use.

例如:list_selector_read.xmllist_selector_unread.xml.

您需要做的就是将所有内容设置为透明,除了 android:state_window_focused="false" 项.

All you need to do is set everything to transparent except the android:state_window_focused="false" item.

然后在绘制列表时为每一行调用 setBackgroundResource(R.drawable.list_selector_unread/read).

Then when you are drawing your list you call setBackgroundResource(R.drawable.list_selector_unread/read) for each row.

您根本没有在 ListView 上设置 listSelector.这将为您的特定 Android 风格保留默认选择器.

You don't set a listSelector on the ListView at all. That will maintain the default selector for your particular flavor of Android.