Android ListView Selector Color

AndroidAndroid Listview

Android Problem Overview


Hi All,

I have 2 questions regarding a ListView in Android:

  1. How can I get the color of the listview's focused row ? I tried to use the ListView.getSelector() method, which according to its documentation should give me what I'm looking for, but it's giving me a Drawable object which I don't know how to retrieve the color from (if possible...).

  2. How can I set the color of the listview's focused row ? Here I tried to use the setSelector() method on the listview, passing it a ColorDrawable object, but the result of doing it is that the whole background of the list view is painted in that color... and this is not what I wanted of course...

Thanks!

Android Solutions


Solution 1 - Android

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 - Android

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:

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).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWhiteTigerKView Question on Stackoverflow
Solution 1 - AndroidChristopher OrrView Answer on Stackoverflow
Solution 2 - AndroidRichard Le MesurierView Answer on Stackoverflow