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);
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With