Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: setselector color for listview not working

I have a listview activity in which I set the selector color using the following code. But when I select an item, the whole list gets highlighted with the selector color, which I don't want. Where Am I doing wrong? Any help is appreciated.

ListView lv = getListView();
lv.setFocusableInTouchMode(true);
lv.setBackgroundColor(Color.WHITE);
lv.setSelector(R.color.blue);
like image 672
Vivek Avatar asked Dec 03 '10 04:12

Vivek


2 Answers

Use this way to use Selector
Create a xml in res/drawable and set the color for different event state
Then this xml as Selector
For example, let res/drawable/selector.xml

<?xml version="1.0" encoding="utf-8"?>
   <selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true"   
    android:drawable="@color/gray" />
</selector>

Then declare gray in your res\values\colors.xml

<color name="gray">#808080</color>

Then set selector as

lv.setSelector( R.drawable.selector);
like image 144
Labeeb Panampullan Avatar answered Oct 20 '22 01:10

Labeeb Panampullan


There's no need to make res/drawable/selector.xml.
Just add these lines in your onCreate method:

StateListDrawable selector = new StateListDrawable();
selector.addState(new int[]{android.R.attr.state_pressed}, new ColorDrawable(R.color.pressed_state_color));
selector.addState(new int[]{-android.R.attr.state_pressed}, new ColorDrawable(R.color.normal_state_color));
lv.setSelector(selector);

Sorry, I haven't enough reputation to add comments to previous answers.

like image 25
DmitryDzz Avatar answered Oct 19 '22 23:10

DmitryDzz