简体   繁体   English

在Android Spinner中从layout.xml设置常量选择

[英]Set constant choices in Android Spinner from layout.xml

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. 当然,我可以从Activity类中动态添加数据,但是我想知道xml本身是否可以执行此操作。

All of the choices that I want to appear in the spinner are present in arrays.xml. 我想出现在微调器中的所有选择都在arrays.xml中。 Is there a way to plug in this data into the Spinner? 有没有办法将此数据插入微调器?

plug this into your spinner assuming that you have properly created you xml array... 假设您已经正确创建了xml数组,请将其插入微调框...

    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: 这对我有用,它从项目资源中加载了一个名为“ count”的字符串数组:

        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: 这是我的资源文件(res / values / arrays.xml),其中包含字符串数组:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM