Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add item in Spinner Android [duplicate]

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);
like image 548
MilanNz Avatar asked Jul 18 '14 12:07

MilanNz


2 Answers

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>
like image 91
madteapot Avatar answered Oct 27 '22 00:10

madteapot


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:

http://developer.android.com/reference/android/widget/ArrayAdapter.html#ArrayAdapter%28android.content.Context,%20int,%20java.util.List%3CT%3E%29

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.

like image 36
user1841702 Avatar answered Oct 27 '22 01:10

user1841702