Create spinner from array

Create a sinner and an adapter, link the two then add to the layout. Use array from strings xml file or created programmatically.

LinearLayout myLayout = (LinearLayout) findViewById(R.id.layout1);
ArrayList spinnerArray = new ArrayList();
	    spinnerArray.add("a");
	    spinnerArray.add("b");
	    spinnerArray.add("c");

Spinner spinner = new Spinner(this);
//default spinner layout
ArrayAdapter adapter = new ArrayAdapter(this, 
	    		android.R.layout.simple_spinner_dropdown_item, spinnerArray);
spinner.setAdapter(adapter);
myLayout.addView(spinner);

To use array in strings xml file and own layout:

ArrayAdapter adapter = ArrayAdapter.createFromResource(this,
R.array.letter_list, R.layout.my_spinner_item);

where strings xml file contains

<string-array name="letter_list">
 <item>x</item>
 <item>y</item>
 <item>z</item>
</string-array>

and you have a layout called my_spinner_item containing something like:

<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@android:id/text1"
    style="@style/spinnerItemStyle"
    android:singleLine="true"
    android:layout_width="10dp"
    android:layout_height="wrap_content"
    android:maxLength="1"
    android:ellipsize="marquee" />

You can also override the drop down layout.

adapter.setDropDownViewResource(R.layout.my_dropdown_item);

This is a simple way (found in stackoverflow) to remove the down arrow from the spinner (API 16 onward).

spinner.setBackground(getResources().getDrawable(android.R.drawable.btn_default));

or in xml:

android:background="@android:drawable/btn_default"

A spinner can be populated from a simple array.

Integer[] items = new Integer[]{4,3,2,1};
//Use this one if you just want the standard item layout
//ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, items);
//or this one if you want your own layout
ArrayAdapter adapter = new ArrayAdapter(this,R.layout.spinner_item, items);
spin.setAdapter(adapter);

 

This entry was posted in Android. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *