Sunday, July 18, 2010

Combo box / Drop down list box in Android

As usual doing something simple in Android is frustrating - this time: a simple Combo (or DropDownList). The little and important tweak - calling "setDropDownViewResource" to set the style of the items in the dialog box.

XML:
<spinner id="@+id/spinner" layout_width="wrap_content" android:layout_height="wrap_content" />

Code to add the data:

Spinner spinner = (Spinner)this.findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_spinner_item,
new String[] { "1", "2", "3" });
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);


A common task is to populate a spinner using a string array defined in a resource file. Here's a function which do just that:

public static void populateSpinnerWithArray(Spinner spinner, int stringArrayResId) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
spinner.getContext(),
android.R.layout.simple_spinner_item,
spinner.getContext().getResources().getStringArray(stringArrayResId));
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}

4 comments:

Unknown said...

very nice. thx

Рабинович said...

Hi, after adding snippet <spinner id="@+id/spinner" .... to main.xml and cleaning I retrieve follow warning: warning: found plain 'id' attribute; did you mean the new 'android:id' name? How to fix ?

Unknown said...

Excellent thank u so much

Unknown said...
This comment has been removed by the author.