4

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?

kshubham07
  • 341
  • 1
  • 3
  • 15
  • 1
    This wasn't hard to find (Google android populate spinner xml): https://stackoverflow.com/questions/4029261/populating-spinner-directly-in-the-layout-xml/4029623 – Juan Sep 02 '18 at 12:48

2 Answers2

5

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>
Paris B. G.
  • 374
  • 1
  • 3
  • 14
1

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>
Vishal Sharma
  • 1,051
  • 2
  • 8
  • 15
  • This is precisely what I did not want. As all the options are hard-coded, I figured there must be some way to plug them in statically. This method sure works but is an overkill. – kshubham07 Sep 02 '18 at 19:46