Reputation: 4636
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);
Upvotes: 8
Views: 17580
Reputation: 34833
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);
Upvotes: 26
Reputation: 416
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.
Upvotes: 3
Reputation: 146
Answers here doesn't work for custom views in ListView because of invalid background. Solution is to set the background of each item to android:background="?android:attr/activatedBackgroundIndicator"
. Here is example:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="?android:attr/activatedBackgroundIndicator">
<!-- your item content-->
</LinearLayout>
After that, StateListDrawable works as expected.
Source: http://www.michenux.net/android-listview-highlight-selected-item-387.html,
Upvotes: 0
Reputation: 359
Thanks for your example, it worked better for me this way...Try this instead.
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_pressed="true" android:drawable="@color/gray" />
</selector>
Then declare gray in your res\values\strings.xml
<color name="gray">#808080</color>
Then set selector as
lv.setSelector( R.drawable.selector);
lv.setDrawSelectorOnTop(true); // if you have background Drawable on your listView
Upvotes: 2
Reputation: 11
You must set
android:state_selected = "true"
to
android:state_selected = "false"
Upvotes: 0