Set constant choices in Android Spinner from layout.xml

Viewed 938

I have a spinner in my layout that I would like to populate with pre-determined, hard-coded data.

Of course I can dynamically add the data from my Activity class, but I want to know if there is a way to do this in the xml itself.

All of the choices that I want to appear in the spinner are present in arrays.xml. Is there a way to plug in this data into the Spinner?

2 Answers

plug this into your spinner assuming that you have properly created you xml array...

    android:drawSelectorOnTop="true"
    android:entries="@array/array_name"

Your String Resources you should add the array like so...

 <string-array name="array_name">
    <item>Array Item One</item>
    <item>Array Item Two</item>
    <item>Array Item Three</item>
</string-array>

This worked for me with a string-array named “count” loaded from the projects resources:

        Spinner spinnerCount = (Spinner)findViewById(R.id.spinner_counts);
        ArrayAdapter<String> spinnerCountArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, getResources().getStringArray(R.array.count));
        spinnerCount.setAdapter(spinnerCountArrayAdapter);


let me know if it will fulfill your requirements.

This is my resource file (res/values/arrays.xml) with the string array:

        <?xml version="1.0" encoding="utf-8"?>
        <resources>
            <string-array name=“count”>
                <item>0</item>
                <item>5</item>
                <item>10</item>
                <item>100</item>
                <item>1000</item>
                <item>10000</item>
            </string-array>
        </resources>
Related