最近項目有個需求。
實現對筆記列表進行批量刪除,功能本身實現比較容易。
網上也有很多demo參考。但是這個項目不太一樣,因為使用的是SimpleCursorAdapter綁定ListView,網上大多數都是ArrayAdapter、SimpleAdapter、BaseAdapter的例子。故而這裡有必要記錄一下解決的辦法。
先來看下別人怎麼實現的:
實現批批量刪除網上大致有以下幾種方式:
1.ArrayAdapter+ListView+CheckBox:https://theopentutorials.com/tutorials/android/listview/android-multiple-selection-listview/
2.BaseAdapter+ListView+CheckBox:https://schimpf.es/listview-with-checkboxes-inside/
3.使用ViewBinder添加CheckBox:https://hi.baidu.com/xghhy/item/391caf9db4c36cdc1e427179
—————————————————————————
解決方法:
1.繼承SimpleCursorAdapter,重寫getView方法
2.在自定義的適配器中添加一個集合,保存被選中的listView條目的id
3.對外提供一個獲取被選中條目id集合的方法
public class CheckBoxAdapter4TextNote extends SimpleCursorAdapter { private ArrayList<Integer> selection = new ArrayList<Integer>();//記錄被選中條目id private int mCheckBoxId = 0;//listView條目的樣式對應的xml資源文件名(必須包含checkbox) private String mIdColumn;//數據庫表的id名稱 public CheckBoxAdapter4TextNote(Context context, int layout, Cursor c, String[] from, int[] to, int checkBoxId, String idColumn, int flags) { super(context, layout, c, from, to, flags); mCheckBoxId = checkBoxId; mIdColumn = idColumn; } @Override public int getCount() { return super.getCount(); } @Override public Object getItem(int position) { return super.getItem(position); } @Override public long getItemId(int position) { return super.getItemId(position); } @Override public View getView(final int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); final CheckBox checkbox = (CheckBox) view.findViewById(mCheckBoxId); checkbox.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Cursor cursor = getCursor(); cursor.moveToPosition(position); checkbox.setChecked(checkbox.isChecked()); if(checkbox.isChecked())//如果被選中則將id保存到集合中 { selection.add(cursor.getInt(cursor.getColumnIndex(mIdColumn))); } else//否則移除 { selection.remove(new Integer(cursor.getInt(cursor.getColumnIndex(mIdColumn)))); Toast.makeText(context, "has removed " + cursor.getInt(cursor.getColumnIndex(mIdColumn)), 0).show(); } } }); return view; } /返回集合 public ArrayList<Integer> getSelectedItems() { return selection; } }
調用:
List<Integer> bn = XXX.getSelectedItems(); for(int id : bn) { //TODO 執行刪除操作 }