Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ListView Selector Color

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!

like image 436
WhiteTigerK Avatar asked Jan 10 '10 18:01

WhiteTigerK


2 Answers

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> 
like image 183
Christopher Orr Avatar answered Sep 24 '22 22:09

Christopher Orr


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

like image 36
Richard Le Mesurier Avatar answered Sep 23 '22 22:09

Richard Le Mesurier