How to set Android Spinner (drop down) array data from Java code

As a quick note, this source code shows how to set the data (array) on an Android Spinner (also known as a dropdown list, or drop down list) from Java code:

// set the spinner data programmatically, from a string array or list

// (1) get a reference to the spinner
Spinner spinner1 = (Spinner)qbTableLayout.findViewById(R.id.spinner1);

// (2) create a simple static list of strings
List<Integer> spinnerArray = new ArrayList<>();
spinnerArray.add(10);
spinnerArray.add(11);

// (3) create an adapter from the list
ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(
    getActivity(),
    android.R.layout.simple_spinner_item,
    spinnerArray
);

//adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

// (4) set the adapter on the spinner
spinner1.setAdapter(adapter);

I use that code in the onCreateView method of an Android Fragment.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.