如何从 arrays.xml 文件中获取字符串数组 [英] How to get String Array from arrays.xml file
本文介绍了如何从 arrays.xml 文件中获取字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只是想从我的 arrays.xml
中的数组中显示一个列表.当我尝试在模拟器中运行它时,我收到一条强制关闭消息.
I am just trying to display a list from an array that I have in my arrays.xml
. When I try to run it in the emulator, I get a force close message.
如果我在java文件中定义数组
If I define the array in the java file
String[] testArray = new String[] {"one","two","three","etc"};
它有效,但是当我使用
it works, but when I use
String[] testArray = getResources().getStringArray(R.array.testArray);
它不起作用.
这是我的 Java 文件:
Here is my Java file:
package com.xtensivearts.episode.seven;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class Episode7 extends ListActivity {
String[] testArray = getResources().getStringArray(R.array.testArray);
/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create an ArrayAdapter that will contain all list items
ArrayAdapter<String> adapter;
/* Assign the name array to that adapter and
also choose a simple layout for the list items */
adapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
testArray);
// Assign the adapter to this ListActivity
setListAdapter(adapter);
}
}
这是我的arrays.xml
文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<array name="testArray">
<item>first</item>
<item>second</item>
<item>third</item>
<item>fourth</item>
<item>fifth</item>
</array>
</resources>
推荐答案
你不能用这种方式初始化你的 testArray
字段,因为应用程序资源还没有准备好.
You can't initialize your testArray
field this way, because the application resources still aren't ready.
只需将代码更改为:
package com.xtensivearts.episode.seven;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class Episode7 extends ListActivity {
String[] mTestArray;
/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create an ArrayAdapter that will contain all list items
ArrayAdapter<String> adapter;
mTestArray = getResources().getStringArray(R.array.testArray);
/* Assign the name array to that adapter and
also choose a simple layout for the list items */
adapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
mTestArray);
// Assign the adapter to this ListActivity
setListAdapter(adapter);
}
}
这篇关于如何从 arrays.xml 文件中获取字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文