Android - 从资源中检索字符串数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10532907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android - retrieve string array from resources
提问by Yuen Tong
Below is the code that i made to retrieve the string array item:
下面是我用来检索字符串数组项的代码:
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);
}
This is the strings.xml file:
这是 strings.xml 文件:
<string-array name="menu">
<item>1</item>
<item>2</item>
<item>3</item>
</string-array>
However, the R.array.menuhaving this issue to compile: As of ADT 14, resource fields cannot be used as switch cases. Invoke this fix to get more information.
然而,R.array.menu有这个问题需要编译:从 ADT 14 开始,资源字段不能用作 switch case。调用此修复程序以获取更多信息。
采纳答案by c2dm
for(int i = 0;i<menuArray.length; i++)
{
Button b = new Button(this);
b.setText(menuArray[i]);
ll.addView(b);
}
Delete the below statement
删除下面的语句
try {
x = count();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
and try to give layout height and width to all Layouts..
并尝试为所有布局提供布局高度和宽度。
回答by Suragch
How to retrieve a string array from resources:
如何从资源中检索字符串数组:
array.xml
数组.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>
Code
代码
String[] stringArray = getResources().getStringArray(R.array.my_string_array);
(The OP already had their question answered but based on the question title, other people may come here looking for this answer.)
(OP 已经回答了他们的问题,但根据问题标题,其他人可能会来这里寻找这个答案。)