Practice Problem: How can you add items programatically to a
Spinner widget?
Hint: use an ArrayAdapter object.
Ans: Add a Spinner widget to the layout, with id set to
spinner1. Then
- place the array of Integer objects to display in the spinner in an array list,
- set up an ArrayAdapter object that connects the spinner to the array list.
Here is the Java code:
// Set up array list.
ArrayList<Integer> arrList = new ArrayList<Integer>( );
for(int n = 1001; n <= 1005; n++) {
arrList.add(n);
}
// Set up array adapter.
ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(
this, android.R.layout.simple_list_item_1, arrList);
spinner1.setAdapter(adapter);