Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting background color for Spinner Item on selection

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?

like image 234
Ajn Avatar asked Sep 28 '11 13:09

Ajn


2 Answers

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"/>  
like image 58
Hanry Avatar answered Oct 13 '22 00:10

Hanry


  1. Create custom View layout (e.g. from TextView)
  2. Create Selector and set it as a background of that view
  3. 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

like image 33
Marqs Avatar answered Oct 13 '22 02:10

Marqs