我創建了一個具有複選框的自定義ListView。我想刪除「刪除」菜單選項選擇中的選定項目。 我正在處理CheckBox上的onCheckedChanged事件。在這裏我維護一個ArrayList來記下所選元素的位置。現在,當用戶選擇「刪除」菜單項時,我會從ListAdapter的ArrayList中刪除選擇的項目。錯誤的列表項被刪除,而不是使用自定義列表適配器選擇的項目
下面是我的代碼,
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
names = new ArrayList<String>();
names.add("first");
names.add("second");
names.add("three");
names.add("four");
names.add("five");
names.add("six");
names.add("seven");
names.add("eight");
names.add("nine");
listAdapter = new SelfAdapter(this,names);
this.setListAdapter(listAdapter);
}
@Override
public boolean onOptionsItemSelected(MenuItem menuItem){
int menuId = menuItem.getItemId();
ArrayList<Integer> selectedItems;
switch(menuId){
case R.id.delitem:
Log.d(TAG,"del item selected");
selectedItems = listAdapter.getSelected();
**//pick the selected position items and delete them from the
// listadapter arraylist**
for(Integer element: selectedItems){
Log.d(TAG,"Selected:"+element.toString());
names.remove(element.intValue());
listAdapter.notifyDataSetChanged();
}
}
return true;
}
下面是自定義適配器的代碼,
}
現在的問題是,如果選擇第1,第2項(例如)然後我看到錯誤的項目被刪除,並在完全錯誤後填充listview。後來如果我試圖刪除它拋出的「索引越界異常」的項目。我猜getView方法中的代碼出錯了。
有人可以幫助我找出在這裏做錯了什麼。
感謝
你能提供具體的問題嗎?選擇第一和第二項時,哪些項目會被刪除?之後listview有什麼用? –
@Ted Hopp - 無論我選擇的項目被刪除的項目是完全不同的(沒有模式)...說如果我選擇第一和第二項目,然後刪除第八和第九項目..但這只是一個例子。 ..沒有一定的模式 – droidsites