无法在 ListView 中修改 ArrayAdapter:UnsupportedOperationException [英] Unable to modify ArrayAdapter in ListView: UnsupportedOperationException

查看:27
本文介绍了无法在 ListView 中修改 ArrayAdapter:UnsupportedOperationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个包含姓名的列表.该列表应该是可修改的(添加、删除、排序等).但是,每当我尝试更改 ArrayAdapter 中的项目时,程序就会崩溃,并出现 java.lang.UnsupportedOperationException 错误.这是我的代码:

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:

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?

推荐答案

我自己尝试过...发现它不起作用.所以我查看了 ArrayAdapter 并找出问题所在.ArrayAdapter 在被数组初始化后,将数组转换为不可修改的 AbstractList(List).

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.

解决方案使用 ArrayList 而不是在初始化 ArrayAdapter 时使用数组.

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

干杯!

这篇关于无法在 ListView 中修改 ArrayAdapter:UnsupportedOperationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆