Android : Fill Spinner From Java Code Programmatically

Rana Osama picture Rana Osama · Aug 12, 2012 · Viewed 110.9k times · Source

How do you fill a spinner from java code programmatically?

I have a spinner in the layout like this:

 <Spinner
     android:id="@+id/consultation_deseases"
     android:layout_width="@dimen/bigSpinnerWidth"
     android:layout_height="@dimen/bigSpinnerHeight"
     android:prompt="@string/disease_prompt" />

With java code I need to create the adapter and add the items.

Answer

WIllJBD picture WIllJBD · Aug 12, 2012
// you need to have a list of data that you want the spinner to display
List<String> spinnerArray =  new ArrayList<String>();
spinnerArray.add("item1");
spinnerArray.add("item2");

ArrayAdapter<String> adapter = new ArrayAdapter<String>(
    this, android.R.layout.simple_spinner_item, spinnerArray);

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner sItems = (Spinner) findViewById(R.id.spinner1);
sItems.setAdapter(adapter);

also to find out what is selected you could do something like this

String selected = sItems.getSelectedItem().toString();
if (selected.equals("what ever the option was")) {
}