我只是想显示我的 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>
原文由 Soren 发布,翻译遵循 CC BY-SA 4.0 许可协议
您不能以这种方式初始化您的
testArray
字段,因为应用程序资源还没有准备好。只需将代码更改为: