Add Item to Spinner

Asked

Viewed 3,867 times

0

2 answers

6

You can declare a String array and include in it

Example:

String spinnerArray[] = {"Item1", "Item2"};

And then include in standard Adapter:

ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, spinnerArray);

spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
seu_spinner.setAdapter(spinnerAdapter);

5


Basically there are two ways to add item to Spinner, providing a list with an array of strings defined in a string resource file (string Resource) and programmatically:

XML

To insert the list in Spinner, just create a string-array in your file strings.xml. Behold:

xml strings.

<string name="linguagem_prompt">Escolha uma linguagem</string>
<string-array name="linguagens">
    <item>Java</item>
    <item>Python</item>
    <item>PHP</item>
    <item>Ruby</item>
</string-array>

Successively, activity_main.xml and set android: strings.xml.

activity_main.xml

<Spinner
    android:id="@+id/spinner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:entries="@array/linguagens"
    android:prompt="@string/linguagem_prompt" />

Programmatically

Mainactivity.class

Spinner spinner = (Spinner) findViewById(R.id.spinner);
List<String> linguagens = new ArrayList<>(Arrays.asList("Java","Python","PHP","Ruby"));

ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
    android.R.layout.simple_spinner_item, linguagens );
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

spinner.setAdapter(dataAdapter);

activity_main.xml

<Spinner
    android:id="@+id/spinner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:prompt="@string/linguagem_prompt" />

For more details on Spinner, see in the documentation.

  • Exceptional. Thank you very much !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.