Android ListView Selector Color
Solution 1:
The list selector drawable is a StateListDrawable
— it contains reference to multiple drawables for each state the list can be, like selected, focused, pressed, disabled...
While you can retrieve the drawable using getSelector()
, I don't believe you can retrieve a specific Drawable
from a StateListDrawable
, nor does it seem possible to programmatically retrieve the colour directly from a ColorDrawable
anyway.
As for setting the colour, you need a StateListDrawable
as described above. You can set this on your list using the android:listSelector
attribute, defining the drawable in XML like this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:state_focused="true"
android:drawable="@drawable/item_disabled" />
<item android:state_pressed="true"
android:drawable="@drawable/item_pressed" />
<item android:state_focused="true"
android:drawable="@drawable/item_focused" />
</selector>
Solution 2:
TO ADD: @Christopher's answer does not work on API 7/8 (as per @Jonny's correct comment) IF you are using colours, instead of drawables. (In my testing, using drawables as per Christopher works fine)
Here is the FIX for 2.3 and below when using colours:
- Android: Entire ListView changes color on focus, not just ListView child item
As per @Charles Harley, there is a bug in 2.3 and below where filling the list item with a colour causes the colour to flow out over the whole list. His fix is to define a shape
drawable containing the colour you want, and to use that instead of the colour.
I suggest looking at this link if you want to just use a colour as selector, and are targeting Android 2 (or at least allow for Android 2).