我只是想显示我的数组中的列表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 adapter;
/* Assign the name array to that adapter and also choose a simple layout for the list items */ adapter = new ArrayAdapter ( this, android.R.layout.simple_list_item_1, testArray);
// Assign the adapter to this ListActivity setListAdapter(adapter); }
} 这是我的arrays.xml档案
first second third fourth fifth 问题来源于stack overflow您无法以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);
}
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。