Android 无法在 ListView 中修改 ArrayAdapter:UnsupportedOperationException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3200551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unable to modify ArrayAdapter in ListView: UnsupportedOperationException
提问by Ryan
I'm trying to make a list containing names. This list should be modifiable (add, delete, sort, etc). However, whenever I tried to change the items in the ArrayAdapter, the program crashed, with java.lang.UnsupportedOperationException
error. Here is my code:
我正在尝试制作一个包含姓名的列表。此列表应该是可修改的(添加、删除、排序等)。但是,每当我尝试更改 ArrayAdapter 中的项目时,程序就会崩溃并java.lang.UnsupportedOperationException
出现错误。这是我的代码:
ListView panel = (ListView) findViewById(R.id.panel);
String[] array = {"a","b","c","d","e","f","g"};
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, array);
adapter.setNotifyOnChange(true);
panel.setAdapter(adapter);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
adapter.insert("h", 7);
}
});
I tried insert, remove and clear methods, and none of them worked. Would someone tell me what I did wrong?
我尝试了插入、删除和清除方法,但都没有奏效。有人会告诉我我做错了什么吗?
回答by st0le
I tried it out, myself...Found it didn't work. So i check out the source code of ArrayAdapterand found out the problem. The ArrayAdapter, on being initialized by an array, converts the array into a AbstractList (List) which cannot be modified.
我自己试过了……发现它不起作用。于是我查看了ArrayAdapter的源代码,发现了问题所在。ArrayAdapter 在由数组初始化时,将数组转换为无法修改的 AbstractList(列表)。
SolutionUse an ArrayList<String>
instead using an array while initializing the ArrayAdapter.
解决方案使用的ArrayList<String>
,而不是使用数组初始化时一个ArrayAdapter。
String[] array = {"a","b","c","d","e","f","g"};
ArrayList<String> lst = new ArrayList<String>(Arrays.asList(array));
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, lst);
Cheers!
干杯!