Teo
Teo

Reputation: 3442

Android dynamically populate Drop Down List

I would like to dynamically populate a drop down list . I would make a request to a server , get my data from there and according to my data ( for example I'll take some ids) I would like to make the list bigger/ smaller. The example that I found on developer.android was a static one , since the names in the list were written in the strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="planet_prompt">Choose a planet</string>
    <string-array name="planets_array">
        <item>Mercury</item>
        <item>Venus</item>
        <item>Earth</item>
        <item>Mars</item>
        <item>Jupiter</item>
        <item>Saturn</item>
        <item>Uranus</item>
        <item>Neptune</item>
    </string-array>
</resources>

Full code here.

Upvotes: 3

Views: 22255

Answers (2)

Hiral Vadodaria
Hiral Vadodaria

Reputation: 19250

ArrayList<String> options=new ArrayList<String>();

options.add("option 1");
options.add("option 2");
options.add("option 3");

// use default spinner item to show options in spinner
 ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,options);
mSpinner.setAdapter(adapter);

You can also set a particular item to be selected using:

mSpinner.setSelection(options.indexOf("option 2"));

EDIT :

You can also use your custom xml file to show spinner item,like-

ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.custom_spinner_item,options);

Upvotes: 12

Paresh Mayani
Paresh Mayani

Reputation: 128428

I suggest you to create an ArrayList of all the objects/Strings that you are getting in response and create an adapter with the same ArrayList. Once you have an adapter then you can easily set it inside the Spinner.

Upvotes: 0

Related Questions