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?
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"/>
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
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