我正在尝试编写一个简单的代码,当用户单击一个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,如果可以的话,请为初学者解释清楚该怎么做。
提前谢谢你。
最佳答案
你可以使用:
String[] arraylist = {"a", "b", "c", "d"};
List<String> list = new ArrayList<String>();
Collections.addAll(list, arraylist);
Arrays.asList()
只生成指向arrayList
的列表,该列表仍然只是字符串的基本数组。而且不能在基元数组上执行类似remove()
的复杂操作。Collections.addAll()
用您的list
值填充真正的arraylist
。