RecyclerView与CheckBox结合使用
RecyclerView中每个item中存放CheckBox,实现全选,全不选,删除选中数据,全部删除等功能
1.界面的效果
文章图片
234231730223678939.jpg 2.Adapter
public class MyRecyclerViewAdapter extends RecyclerView.Adapter implements View.OnClickListener {
private Context context;
private List list;
private List booleanlist=new ArrayList<>();
public MyRecyclerViewAdapter(Context context) {
this.context=context;
list=new ArrayList<>();
}public MyRecyclerViewAdapter(Context context,List list) {
this.context=context;
this.list=list;
for (int i = 0;
i < list.size();
i++) {
//设置默认的显示
booleanlist.add(false);
}
}public void addData(List strings){list.addAll(strings);
for (int i = 0;
i < strings.size();
i++) {
booleanlist.add(false);
}
notifyDataSetChanged();
}//更改集合内部存储的状态
public void initCheck(boolean flag) {for (int i = 0;
i < list.size();
i++) {
//更改指定位置的数据
booleanlist.set(i,flag);
}
}@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
MyViewHolder holder = new MyViewHolder(LayoutInflater.from(
context).inflate(R.layout.list_item1, parent,
false));
return holder;
}@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.tv.setText(list.get(position));
holder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//用集合保存当前的状态
booleanlist.set(position,isChecked);
}
});
holder.cb.setChecked(booleanlist.get(position));
}@Override
public int getItemCount() {
return list.size();
}//清空所有数据
public void deleteAllData() {list.clear();
booleanlist.clear();
notifyDataSetChanged();
}//删除选中的数据
public void deletingData() {int y=0;
for (int i = 0;
i < list.size();
i++) {
if(booleanlist.get(i)!=null && booleanlist.get(i) ) {
list.remove(i);
booleanlist.remove(i);
y++;
i--;
}
}
notifyDataSetChanged();
if(y==0){
Toast.makeText(context, "没有选中的要删除的数据", Toast.LENGTH_SHORT).show();
}
}public void selectAll(){
initCheck(true);
notifyDataSetChanged();
}
public void unSelectAll(){
initCheck(false);
notifyDataSetChanged();
}/**
* ViewHolder的类,用于缓存控件
*/
class MyViewHolder extends RecyclerView.ViewHolder {CheckBox cb;
TextView tv;
public MyViewHolder(View view) {
super(view);
cb = (CheckBox) view.findViewById(R.id.list_item1_cb);
tv = (TextView) view.findViewById(R.id.list_item1_tv);
}}
}
3.说明
CheckBox 需要设置当前的选中状态,每次改变状态的时候,要记住当前的选中状态。
RecyclerView使用,详情请参考:
https://www.jianshu.com/p/4ca091bb8638
推荐阅读
- JAVA(抽象类与接口的区别&重载与重写&内存泄漏)
- Docker应用:容器间通信与Mariadb数据库主从复制
- 《真与假的困惑》???|《真与假的困惑》??? ——致良知是一种伟大的力量
- 第326天
- Shell-Bash变量与运算符
- 逻辑回归的理解与python示例
- Guava|Guava RateLimiter与限流算法
- 我和你之前距离
- CGI,FastCGI,PHP-CGI与PHP-FPM
- 原生家庭之痛与超越