android开发 recycleview的item中加入checkbox实现批量选择条目(复用时防止checkbox勾选状态错乱)

最近做一个图库功能,需要批量编辑图片,使用recycleview展示图片,并在每个item中加入一个checkbox。
item的布局如下

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@color/white"
    android:padding="@dimen/dim3">

    <ImageView
        android:id="@+id/iv_photo"
        android:layout_width="@dimen/dim176"
        android:layout_height="@dimen/dim200"
        android:layout_margin="2dp"
        android:scaleType="centerCrop"
        android:src="@drawable/im_default_load_image" />

    <CheckBox
        android:id="@+id/cb_photo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@id/iv_photo"
        android:layout_alignTop="@id/iv_photo"
        android:checked="false"/>
</RelativeLayout>

然后在条目的点击事件中设置checkbox的选择状态就可以了。
但是在这样在滚动之后,条目复用的时候checkbox的选择状态也会被复用,导致后面没有勾选的条目也会变成勾选状态,或者勾选了的滚动后又变成未勾选。
要解决这个问题 需要在适配器中添加一个Boolean型的集合,来存放每个位置的条目的勾选状态。

public List<Boolean> flag;

拿到数据的时候 先把所有的都设为false。

for (int i = 0; i < data.size(); i++) {
               adapter.flag.add(false);
           }

在适配器的onBindViewHolder中设置checkbox的状态,从flag中获得。

holder.cb_photo.setChecked(flag.get(position));

在点击事件中修改falg中相应的状态

adapter.flag.set(position, checkBox.isChecked());

这样每次在复用view的时候 checkbox的状态都会重新设置,不会再出现乱七八糟的问题了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值