I am using the Spinner control in my code. I want the item to get highlighted (i.e., background color changed for that item) on selection. How can this be achieved?
Asked
Active
Viewed 2.7k times
2 Answers
9
create a xml: for ex:mybg.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false" android:drawable="@color/anyColor" />
<item android:drawable="@android:color/transparent" />
</selector>
and in your activity xml
do
<Spinner...............
android:drawSelectorOnTop="true"
android:background="@drawable/mybg"/>

Hanry
- 5,481
- 2
- 40
- 53
3
- Create custom View layout (e.g. from TextView)
- Create Selector and set it as a background of that view
- Set Spinner with custom view
Selector: custom_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true"
android:state_pressed="false"
android:drawable="@color/light_grey" />
<item android:state_focused="true"
android:state_pressed="true"
android:drawable="@color/light_grey" />
<item android:state_focused="false"
android:state_pressed="true"
android:drawable="@color/light_grey" />
<item android:state_selected="true" android:drawable="@color/light_grey"/>
<item android:drawable="@color/white" />
</selector>
Custom View layout: my_simple_item
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:lines="1"
android:padding="5dip"
android:background="@drawable/custom_selector"/>
Initialise Spinner:
String[] items = new String[] {"One", "Two", "Three"};
Spinner spinner = (Spinner) findViewById(R.id.mySpinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.my_simple_item, items);
Hope this helps

Marqs
- 17,800
- 4
- 30
- 40
-
1When scroll using wheel of my mouse no any effect. Items should be light_grey but instead they are orange(default color for android 2.2) see my question http://stackoverflow.com/questions/14737811/spinner-does-not-apply-dropdownselector-attribute – vsvydenko Feb 07 '13 at 10:31