我試圖做一個簡單的代碼,當用戶點擊它時刪除一個ListView項目。 我的代碼:從ListView和ArrayAdapter中刪除項目
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,如果可以,請解釋清楚初學者什麼去做。
提前感謝您。
您將不得不從陣列中刪除項目。 –
如何從陣列中移除物品?因爲我創建了新的列表,我無法從數組中刪除項目。 – Dennis
我已經使用'remove()'和'notifyDataSetChanged()'沒有問題。你能發佈完整的堆棧跟蹤嗎? –