How to add item from str in spinner? I tryed with ArrayList, ArrayAdapter but didn't work...
String[] str={"item 1","item 2","item 3"};
Spinner s=(Spinner)findViewById(R.id.spinner);
You can use simple default ArrayAdapter to achieve your requirement dynamically. Below is the code snippet you can follow and modify your onCreate Method to add values in the spinner.
spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> adapter;
List<String> list;
list = new ArrayList<String>();
list.add("Item 1");
list.add("Item 2");
list.add("Item 3");
list.add("Item 4");
list.add("Item 5");
adapter = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
if you want the spinner values to be added statically you can add the array in the xml file and assign the attribute entries
for the spinner. below is the code snippet for that.
Your layout xml file
<Spinner android:id="@+id/spinner"
android:layout_width="fill_parent"
android:drawSelectorOnTop="true"
android:prompt="@string/spin"
android:entries="@array/items" />
In your arrays.xml file
<string-array name="items">
<item>Item 1</item>
<item>Item 2</item>
<item>Item 3</item>
<item>Item 4</item>
<item>Item 5</item>
</string-array>
The Android reference has a good example and instead of using:
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.planets_array, android.R.layout.simple_spinner_item);
as given in the example (this is because the Spinner
is populated from a pre-existing string-array resource defined in an xml file ) you could use the ArrayAdapter
constructor that accepts a List as its argument, as shown at:
You could do this like so:
ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.your_layout,mYourList)
where mYourList could be an ArrayList<String>
where you can store the data that you want to populate your Spinner
with.
Android Spinner
s use the SpinnerAdapter
class.
http://developer.android.com/reference/android/widget/SpinnerAdapter.html