无法修改 ListView 中的 ArrayAdapter: Unsupport tedOperationException

我正在列一个名单。这个列表应该是可修改的(添加、删除、排序等)。但是,每当我试图更改 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);
}
});

我尝试了插入、删除和清除方法,但没有一个奏效。有人能告诉我我做错了什么吗?

38405 次浏览

I tried it out, myself...Found it didn't work. So i check out the source code of ArrayAdapter and found out the problem. The ArrayAdapter, on being initialized by an array, converts the array into a AbstractList (List) which cannot be modified.

Use an ArrayList<String> instead using an array while initializing the 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!