Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing background color of ListView items on Android

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 I would rather not change the selector itself.

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

like image 948
Marek Stój Avatar asked Feb 07 '10 18:02

Marek Stój


People also ask

What is the use of ListView in android?

A list view is an adapter view that does not know the details, such as type and contents, of the views it contains. Instead list view requests views on demand from a ListAdapter as needed, such as to display new views as the user scrolls up or down. In order to display items in the list, call setAdapter(android.


1 Answers

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

For example: list_selector_read.xml and list_selector_unread.xml.

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

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

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

like image 112
Hawkee Avatar answered Oct 16 '22 20:10

Hawkee