我只是想在我arrays.xml
的数组中显示一个列表。当我尝试在模拟器中运行它时,我收到强制关闭消息。
如果我在java文件中定义数组
String[] testArray = new String[] {"one","two","three","etc"};
它有效,但是当我使用
时String[] testArray = getResources().getStringArray(R.array.testArray);
它不起作用。
这是我的Java文件:
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>
答案 0 :(得分:195)
您无法以这种方式初始化testArray
字段,因为应用程序资源尚未就绪。
只需将代码更改为:
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);
}
}
答案 1 :(得分:28)
你的array.xml不对。把它改成这样的
这是array.xml文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="testArray">
<item>first</item>
<item>second</item>
<item>third</item>
<item>fourth</item>
<item>fifth</item>
</string-array>
</resources>
答案 2 :(得分:2)
您的XML并不完全清楚,但如果您将数字设为数字,并且/或在其定义中放置空格,则数组XML可能导致强制关闭。
确保它们被定义为No Leading or Trailing Whitespace