当前位置: 代码迷 >> 综合 >> 【android】ListView+SimpleCursorAdapter+checkbox实现批量删除
  详细解决方案

【android】ListView+SimpleCursorAdapter+checkbox实现批量删除

热度:85   发布时间:2023-12-19 10:19:59.0
最近项目有个需求。
实现对笔记列表进行批量删除,功能本身实现比较容易。
网上也有很多demo参考。但是这个项目不太一样,因为使用的是SimpleCursorAdapter绑定ListView,网上大多数都是ArrayAdapter、SimpleAdapter、BaseAdapter的例子。故而这里有必要记录一下解决的办法。


先来看下别人怎么实现的:
实现批批量删除网上大致有以下几种方式:
1.ArrayAdapter+ListView+CheckBox: http://theopentutorials.com/tutorials/android/listview/android-multiple-selection-listview/
2.BaseAdapter+ListView+CheckBox: http://schimpf.es/listview-with-checkboxes-inside/
3.使用ViewBinder添加CheckBox: http://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>();//记录被选中条目idprivate 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;}@Overridepublic int getCount(){return super.getCount();}@Overridepublic Object getItem(int position){return super.getItem(position);}@Overridepublic long getItemId(int position){return super.getItemId(position);}@Overridepublic 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(){@Overridepublic 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 执行删除操作}

如果没能帮到你,试试这篇文章( http://craftsman1970.blog.51cto.com/3522772/725606 )。