Add Spinner Item [closed]

0

I need to use Spinner in my app ...

I'm having trouble adding elements to the list.

I found it very complicated.

Link: link

Would there be another way to simplify this?

Thank you!

    
asked by anonymous 10.01.2017 / 16:53

2 answers

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 , you only have to create a string-array in your strings.xml file. See:

strings.xml

<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>

Successfully, activity_main.xml and set android: entries with the name created in 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 .

    
10.01.2017 / 17:18
6

You can declare an array of String and include in it

Example:

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

And then add the default 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);
    
10.01.2017 / 16:56