Spinner widget is a drop down list in android. Using spinner, your app can display list of available choices for a particular data element and allow user to select one item from the list.
In this article, I’ll explain populating various formats of data in spinner, properties of spinner, spinner customization, and spinner listener with examples.
To use spinner, first it needs to be defined in layout using Spinner element. Below layout shows how to use spinner in constraint layout.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp">
<Spinner
android:id="@+id/spinnerOfferType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginTop="8dp"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"></Spinner>
</android.support.constraint.ConstraintLayout>
Since spinner populates multiple items like list view, spinner can be populated using adapter. Adapter maps view and data. Below code shows how to populate spinner from string array xml using ArrayAdapter.
Layout for each item and string array, and drop down view are passed to array adapter.
spinnerOfferType = (Spinner)findViewById(R.id.spinnerOfferType);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.offer_types, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerOfferType.setAdapter(adapter);
To populate spinner with data from list of strings, you need to use ArrayAdapter constructor passing item view and ArrayList as shown below.
spinnerOfferType = (Spinner)findViewById(R.id.spinnerOfferType);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, CouponStoreData.getCouponData());
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerOfferType.setAdapter(arrayAdapter);
If you want to know how to select, insert, update and delete data in SQLite, you can read my previous tutorial how to use SQLite database in android.
Here I’ll show how to convert convert cursor to string array list to populate it in spinner.
public List<String> getOfferTypes(){
List<String> offerTypes = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + TABLE_OFFERTYPES;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
offerTypes.add(cursor.getString(0));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return offerTypes;
}
Json data can be populated in spinner by converting JSON into string array list. In this example I am going to show how to convert JSON into string array list and populate it in spinner.
//json string
String offerJson = "{ \"offerTypes\": [ {\"offerType\" : \"Coupons\"}, {\"offerType\" : \"Cashback\"}, {\"offerType\" : \"Deals\"}, {\"offerType\" : \"Top Deals\"}]}";
List<String> offerTypesArrayList = new ArrayList<String>();
//convert json string into array list
try {
JSONObject jObj = new JSONObject(offerJson);
JSONArray offerTypes = jObj.getJSONArray("offerTypes");
for (int i = 0; i < offerTypes.length(); i++) {
JSONObject offertype = offerTypes.getJSONObject(i);
String offerType = offertype.getString("offerType");
offerTypesArrayList.add(offerType);
}
} catch (JSONException e) {
e.printStackTrace();
}
//populate converted json data in spinner
spinnerOfferType = (Spinner) findViewById(R.id.spinnerOfferType);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, offerTypesArrayList);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerOfferType.setAdapter(arrayAdapter);
When an item is selected in spinner, spinner object receives item selected event. To handle item selected event, you need to define listener by implementing AdapterView.OnItemSelectedListener and set it to spinner object.
AdapterView.OnItemSelectedListener has two callback methods, onItemSelected and onNothingSelected. Method onItemSelected is called when an item is selected and method onNothingSelected is called when an item is unselected.
spinnerOfferType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
String item = spinnerOfferType.getSelectedItem().toString();
slectItem.setText(item);
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
You can set spinner mode in xml and in code. In xml, you can set spinner mode using spinnerMode attribute and in code, you can pass spinner mode to one of the Spinner constructors.
Spinner mode setting defines how spinner items are shown when you click spinner to reveal spinner items. Spinner supports two modes, dialog (Spinner.MODE_DIALOG) and dropdown (Spinner.MODE_DROPDOWN) mode. By default, spinner items are shown in dropdown mode. Below screen shot show spinner in dialog mode.
Below screen shot show spinner with prompt. You can set prompt in xml using prompt attribute and in code by calling setPrompt on spinner object. Spinner attribute prompt is applicable only when spinner is in dialog mode. Highlighted prompt with red rectangle below.
You can set background image for popup when spinner is in dialog mode. You can set back ground for popup by calling setPopupBackgroundResource method on spinner.
spinnerOfferType.setPopupBackgroundResource(R.drawable.zoftino);
To change the style of spinner, you need to create item layout and dropdown view and apply styles. In the above examples, we used android provided item layout android.R.layout.simple_spinner_item and dropdown view android.R.layout.simple_spinner_dropdown_item.
To show how to customize spinner style, we will create layouts similar to what we used and apply styles.
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
style="@style/spinnerItemStyleZoftino"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="1"
android:ellipsize="marquee"
android:textAlignment="inherit"
android:paddingBottom="8dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="8dp"></TextView>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
style="@style/spinnerDropDownItemStyleZoftino"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="1"
android:ellipsize="marquee"
android:paddingBottom="8dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="8dp"></CheckedTextView>
<style name="spinnerItemStyleZoftino" parent="android:Widget.TextView.SpinnerItem">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:capitalize">words</item>
<item name="android:textSize">25dp</item>
<item name="android:textColor">#421a85</item>
</style>
<style name="spinnerDropDownItemStyleZoftino" parent="android:TextAppearance.Widget.TextView.SpinnerItem">
<item name="android:textSize">25dp</item>
<item name="android:textColor">#d43003</item>
<item name="android:background">#a1c8bb</item>
</style>