【发布时间】:2015-04-30 09:05:24
【问题描述】:
我有一个用字符串数组填充的简单 ArrayAdapter。
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
inflater.getContext(), android.R.layout.simple_list_item_1,
numbers_text);
当我传入这样的字符串时,一切正常。
String[] numbers_text = new String[] { "one", "two", "three", "four" };
但是当我以这种方式声明字符串时,它会崩溃。
Resources res = getResources();
String[] numbers_text = res.getStringArray(R.array.Planets);
这里有没有我遗漏的逻辑错误?
xml字符串数组:
<string-array name="Planets">
<item>Sun</item>
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
<item>Jupiter</item>
<item>Saturn</item>
<item>Uranus</item>
<item>Neptune</item>
</string-array>
编辑:发布更新后的代码,将字符串声明移到函数中
public class SimpleListFragment extends ListFragment
{
Resources res = getActivity().getResources();
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
String[] numbers_digits = res.getStringArray(R.array.Planets);
new CustomToast(getActivity(), numbers_digits[(int) id]);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String[] numbers_text = res.getStringArray(R.array.Planets);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
inflater.getContext(), android.R.layout.simple_list_item_1,
numbers_text);
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
}
【问题讨论】:
-
但是你在哪里打电话给
getResources()? -
堆栈跟踪会很好......
-
@MD 您好,在您删除答案之前,我尝试了您的解决方案。对不起,我不知道谁对你的回答投了反对票。但仍然崩溃。
-
是的。将其移动到回调之一中,例如
onCreateView -
@atsay714 问题仍然是
getResources()。它位于方法上下文中,例如 getStringArray。我以为很清楚
标签: java android arrays string android-arrayadapter