我正在尝试创建一个简单的代码,用于在用户单击时删除ListView项。 我的代码:
static ArrayAdapter<String> dataAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notifications_list);
String[] arraylist = {"a", "b", "c", "d"};
List<String> list = Arrays.asList(arraylist);
dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
list);
setListAdapter(dataAdapter);
}
public void onListItemClick(ListView l, View v, final int position, long id) {
dataAdapter.remove(dataAdapter.getItem(position));
dataAdapter.notifyDataSetChanged();
}
单击该项时,应用程序崩溃并显示以下错误:
D/AndroidRuntime(31862): Shutting down VM
W/dalvikvm(31862): threadid=1: thread exiting with uncaught exception (group=0x40b4e300)
E/AndroidRuntime(31862): FATAL EXCEPTION: main
E/AndroidRuntime(31862): java.lang.UnsupportedOperationException
E/AndroidRuntime(31862): at java.util.AbstractList.remove(AbstractList.java:638)
E/AndroidRuntime(31862): at java.util.AbstractList$SimpleListIterator.remove(AbstractList.java:75)
E/AndroidRuntime(31862): at java.util.AbstractCollection.remove(AbstractCollection.java:229)
E/AndroidRuntime(31862): at android.widget.ArrayAdapter.remove(ArrayAdapter.java:244)
E/AndroidRuntime(31862): at com.dennis.notifications.NotificationList.onListItemClick(NotificationList.java:113)
E/AndroidRuntime(31862): at android.app.ListActivity$2.onItemClick(ListActivity.java:319)
E/AndroidRuntime(31862): at android.widget.AdapterView.performItemClick(AdapterView.java:298)
E/AndroidRuntime(31862): at android.widget.AbsListView.performItemClick(AbsListView.java:1088)
E/AndroidRuntime(31862): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2861)
E/AndroidRuntime(31862): at android.widget.AbsListView$1.run(AbsListView.java:3535)
E/AndroidRuntime(31862): at android.os.Handler.handleCallback(Handler.java:615)
E/AndroidRuntime(31862): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(31862): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(31862): at android.app.ActivityThread.main(ActivityThread.java:4931)
E/AndroidRuntime(31862): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(31862): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(31862): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
E/AndroidRuntime(31862): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
E/AndroidRuntime(31862): at dalvik.system.NativeStart.main(Native Method)
我是Java和Android的新手,如果可以的话,请为初学者清楚解释一下该做什么 提前感谢你。
答案 0 :(得分:6)
您可以使用:
String[] arraylist = {"a", "b", "c", "d"};
List<String> list = new ArrayList<String>();
Collections.addAll(list, arraylist);
Arrays.asList()
只生成一个指向arrayList
的List,它仍然只是一个原始的字符串数组。并且您无法在基本数组上执行复杂的操作,如remove()
。 Collections.addAll()
使用list
值填充真实arraylist
。