Android学习--实现listview批量删除的功能

继放下了上次的项目两个月之后,领导又有了新的需求,她发现要删除已经到期的倒数日太多,又不能批量删除。所以我就想做一个跟微信一样的,长按弹出菜单,直接删除当前的,或者是多选删除。
这就需要用到checkbox。
首先是修改xml文件。直接在list-item的文字前面加checkbox即可

<Checkbox
    android:id="delete_cb"
    android:width="wrap_content"
    android:height="wrap_content"
    android:visibility="gone"
    />

然后修改count in的xml,增加一个删除按钮。

<Button
    android:id="delete_btn"
    android:width="match_parent"
    android:height="wrap_content"
    android:visibility="gone"
    />

之后就是代码工作了。其实实现不难,要点是给Adapter类增加两个HashMap来记录(其实Arraylist也可以。不过hashmap能有一个对应关系更加自由)

//记录某一项的checkbox是否可见
private HashMap<Integer,Integer> checkBoxVisibility;
//记录某一项的checkbox是否被选择
private HashMap<Integer,Boolean> checkBoxSelected;

记得初始化

checkBoxVisibility=new HashMap<Integer,Integer>();
checkBoxSelected=new HashMap<Integer,Boolean>();
for(int i=0;i<dates.size();i++){
        checkBoxVisibility.put(i,View.GONE);
        checkBoxSelected.put(i, false);             
}

因为每一项都有一个checkbox,所以我们在viewholder中加入

class ViewHolder {
            private LinearLayout countToLayout;
            private TextView change;
            private TextView content;
            private TextView date;
            private CheckBox check;
}

之后getView函数中需要添加代码。如果是新建的项(if (convertView == null)),则要在hashmap中添加,如果是已经有的项(else),则一般都是经过删除或者是新建后顺序变了需要重新调整。
接下来是个卡住的地方,怎么监听checkbox已经被勾选了呢?我们需要在Adapter中加listener。

final int position1=position;//position是当前项的位置
vh.check.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
        checkBoxSelected.put(position1, true);
    }
});

接下来是删除的逻辑:
要点:因为我是用的for来循环,查看哪项是被勾选的,如果是被勾选,则删除在数据库中的数据跟list中的,这里要注意数组不能越界,所以list的下标是顺序减去被删除的数量。

case R.id.delete_btn:
int count=0;
for(int order=0;order<adapter.visibilityMap().size();order++){          if(adapter.selectedMap().get(order)==true){
        Day d=dayLists.get(order-count);
        String content=d.content;
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.delete("CountDays1", "content1=?", new String[] { content });                
        dayLists.remove(order-count);
        count++;
            }
            }
            for(int order=0;order<adapter.getCount();order++){
                adapter.checkBoxSelected.put(order, false);
                adapter.checkBoxVisibility.put(order,View.GONE);
            }
            adapter.notifyDataSetChanged();
            add.setText("新建");
            delete.setVisibility(View.GONE);
            checking=false;
            Toast.makeText(this, "已删除", Toast.LENGTH_SHORT).show();
            break;

还有一些跳转的逻辑就不说了

猜你喜欢

转载自blog.csdn.net/BenjaminYoung29/article/details/52291210