如何从 arrays.xml 文件获取字符串数组

我只是试图显示一个数组中的列表,我在我的 arrays.xml。当我尝试运行它在模拟器中,我得到一个力关闭消息。

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);

it doesnt work.

这是我的 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>
234652 次浏览

不能以这种方式初始化 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);
}
}

Your XML is not entirely clear, but arrays XML can cause force closes if you make them numbers, and/or put white space in their definition.

确保它们的定义类似于“无引导空格”或“尾随空格”

您的 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>

还可以通过以下代码从 xml 获取字符串数组作为 ArrayList

Xml 数组:

    <string-array name="testArray">
<item>first</item>
<item>second</item>
<item>third</item>
<item>fourth</item>
<item>fifth</item>
</string-array>

Kotlin 代码:

val stringArray: ArrayList<String> =  resources.getStringArray(R.array.testArray).toList() as ArrayList<String>