Android - 从资源中检索字符串数组

标签 android string resources

以下是我为检索字符串数组项所做的代码:

String[] menuArray;

@Override
public void onCreate(Bundle savedInstanceState) 
{       
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ScrollView sv = new ScrollView(this);
    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);
    sv.addView(ll);

 // Create an ArrayAdapter that will contain all list items
    ArrayAdapter<String> adapter;

    menuArray = getResources().getStringArray(R.array.menu); 


    for(int i = 0; i < menuArray.length; i++) 
    {
        Button b = new Button(this);
        b.setText(menuArray[i]);
        ll.addView(b);
    }

    this.setContentView(sv);
 }

这是 strings.xml 文件:

 <string-array name="menu">
        <item>1</item>
        <item>2</item>
        <item>3</item>
        </string-array>

但是,R.array.menu 有这个问题要编译: 从 ADT 14 开始,资源字段不能用作 switch case。 调用此修复程序以获取更多信息。

最佳答案

如何从资源中检索字符串数组:

array.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string-array name="my_string_array">
        <item>one</item>
        <item>two</item>
        <item>three</item>
    </string-array>

</resources>

代码

String[] stringArray = getResources().getStringArray(R.array.my_string_array);

(OP 已经回答了他们的问题,但根据问题标题,其他人可能会来这里寻找这个答案。)

关于Android - 从资源中检索字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10532907/

相关文章:

android - AdMob 中介(Android 和 iOS): how to force a network to test it?

c++ - 避免错误的用户输入(当要求的是整数时为字符串)

c# - WPF 从 ResourceDictionary 读取样式到 C# 代码中的控件

java - 在 Resources 文件夹中存储值有多大必要?

android - Holo.Light 主题但有白色溢出点?

Java 循环故障排除

c - 如何正确解析算术表达式中的数字,区分正数和负数?

c++ - g++ __FUNCTION__ 替换时间

localization - 带有新 csproj 的 .NET Standard (1.4) 中的资源文件

java - 如何从 recyclerview 适配器中消除对话框 fragment