RecyclerView中的CheckBox继续检查不同的项目

时间:2015-09-06 20:19:08

标签: android android-recyclerview

这里是我在RecyclerView中的项目的XML

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cvItems"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:layout_margin="2dp"
    card_view:cardElevation="0dp"
    card_view:contentPadding="0dp"
    card_view:cardBackgroundColor="#FFFFFF"
    >

    <LinearLayout
        android:orientation="horizontal"
        android:layout_height="fill_parent"
        android:layout_width="fill_parent">
        <TextView
            android:layout_width="0dip"
            android:layout_height="match_parent"
            android:layout_weight="0.8"
            android:id="@+id/tvContent"
            android:textSize="15dp"
            android:paddingLeft="5dp"
            android:paddingRight="5dp" />
        <CheckBox
            android:id="@+id/cbSelect"
            android:layout_width="0dip"
            android:layout_weight="0.2"
            android:layout_height="match_parent"
            android:button="@drawable/cb_checked"
            android:gravity="center_horizontal"
            android:textAlignment="center"
            android:layout_gravity="center_horizontal" />
    </LinearLayout>
</android.support.v7.widget.CardView>

这里是RecyclerView适配器,它为每个项目增加了上面的布局:

public class AdapterTrashIncome extends RecyclerView.Adapter<AdapterTrashIncome.ViewHolder> {

    private ArrayList<ObjectIncome> myItems = new ArrayList<>();

    public AdapterTrashIncome(ArrayList<ObjectIncome> getItems, Context context){
        try {
            mContext = context;
            myItems = getItems;
        }catch (Exception e){
            Log.e(FILE_NAME, "51: " + e.toString());
            e.printStackTrace();
        }
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public TextView tvContent;
        public CheckBox cbSelect;

        public ViewHolder(View v) {
            super(v);
            tvContent = (TextView) v.findViewById(R.id.tvContent);
            cbSelect = (CheckBox) v.findViewById(R.id.cbSelect);
        }
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
        final ObjectIncome objIncome = myItems.get(position);
        String content = "<b>lalalla</b>";
        holder.tvContent.setText(Html.fromHtml(content));
    }
}

问题是,让我说我在RecyclerView中有10个项目。当我选中项目1,2,3上的复选框时,我向下滚动RecyclerView,突然检查其他一些项目,例如项目8,9。当我再次向上滚动时,检查项目1和3但不检查项目2.知道为什么会发生这种情况吗?

23 个答案:

答案 0 :(得分:128)

这很正常。您没有选中是否选中了复选框。您正在选择一个,而View holder会保持选中状态。您可以在ObjectIncome对象中添加一个布尔变量,并保持项目的选择状态。

你可以看看我的例子。你可以这样做:

public class AdapterTrashIncome extends RecyclerView.Adapter<AdapterTrashIncome.ViewHolder> {

    private ArrayList<ObjectIncome> myItems = new ArrayList<>();

    public AdapterTrashIncome(ArrayList<ObjectIncome> getItems, Context context){
        try {
            mContext = context;
            myItems = getItems;
            }catch (Exception e){
            Log.e(FILE_NAME, "51: " + e.toString());
            e.printStackTrace();
        }
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public TextView tvContent;
        public CheckBox cbSelect;

        public ViewHolder(View v) {
            super(v);
            tvContent = (TextView) v.findViewById(R.id.tvContent);
            cbSelect = (CheckBox) v.findViewById(R.id.cbSelect);
        }
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
        final ObjectIncome objIncome = myItems.get(position);
        String content = "<b>lalalla</b>";
        holder.tvContent.setText(Html.fromHtml(content));

        //in some cases, it will prevent unwanted situations
        holder.cbSelect.setOnCheckedChangeListener(null);

        //if true, your checkbox will be selected, else unselected
        holder.cbSelect.setChecked(objIncome.isSelected());

        holder.cbSelect.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    //set your object's last status
                    objIncome.setSelected(isChecked);
            }
        });

    }
}

答案 1 :(得分:20)

如果您在回收器视图中拥有有限的物品数量,请使用此选项。
我尝试在模型中使用布尔值并保持复选框状态,但在我的情况下它没有帮助。 对我有用的是 this.setIsRecyclable(false);

public class ComponentViewHolder extends RecyclerView.ViewHolder {
    public MyViewHolder(View itemView) {
        super(itemView);
        ....
        this.setIsRecyclable(false);
    }

有关此问题的更多说明,请访问https://developer.android.com/reference/android/support/v7/widget/RecyclerView.ViewHolder.html#isRecyclable()

注意:这是一种解决方法。要正确使用它,您可以参考文档,其中指出“对setIsRecyclable()的调用应始终配对(对setIsRecyclabe(false)的一次调用应始终与稍后调用setIsRecyclable(true)匹配)。可能是嵌套的,因为状态是内部引用计数的。“我不知道如何在代码中执行此操作,如果有人可以提供更多代码。

答案 2 :(得分:14)

简而言之,它是因为回收了视图并再次使用它们!

你怎么能避免这种情况:

1.在onBindViewHolder中检查是否应选中或取消选中复选框。 不要忘记将if和else放在一起

if (...)
    holder.cbSelect.setChecked(true);
else
    holder.cbSelect.setChecked(false);
  1. 放置一个监听器复选框!每当检查过的雕像发生变化时,也会在myItems数组中更新相应的对象!因此,无论何时显示新视图,它都会读取最新的物体雕像。

答案 3 :(得分:9)

您可以使用Model类来跟踪每个recyclerView项目的复选框。 完整参考来自: RecyclerView Checkbox Android

setTag getTag 用于跟踪复选框状态。查看完整参考链接以获取更多信息。它还教授如何将选中的项目发送到 NEXTACTIVITY

制作模型

public class Model {

    private boolean isSelected;
    private String animal;

    public String getAnimal() {
        return animal;
    }

    public void setAnimal(String animal) {
        this.animal = animal;
    }

    public boolean getSelected() {
        return isSelected;
    }

    public void setSelected(boolean selected) {
        isSelected = selected;
    }
}

创建integer.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="btnplusview">1</integer>
    <integer name="btnpluspos">2</integer>
</resources>

最后,适配器看起来像这样:

 import android.content.Context;
 import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
    import android.view.View;
 import android.view.ViewGroup;
 import android.widget.CheckBox;
 import android.widget.TextView;
 import android.widget.Toast;

 import java.util.ArrayList;


  public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {

private LayoutInflater inflater;
public static ArrayList<Model> imageModelArrayList;
private Context ctx;

public CustomAdapter(Context ctx, ArrayList<Model> imageModelArrayList) {

    inflater = LayoutInflater.from(ctx);
    this.imageModelArrayList = imageModelArrayList;
    this.ctx = ctx;
}

@Override
public CustomAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = inflater.inflate(R.layout.rv_item, parent, false);
    MyViewHolder holder = new MyViewHolder(view);

    return holder;
}

@Override
public void onBindViewHolder(final CustomAdapter.MyViewHolder holder, int position) {

    holder.checkBox.setText("Checkbox " + position);
    holder.checkBox.setChecked(imageModelArrayList.get(position).getSelected());
    holder.tvAnimal.setText(imageModelArrayList.get(position).getAnimal());

   // holder.checkBox.setTag(R.integer.btnplusview, convertView);
    holder.checkBox.setTag(position);
    holder.checkBox.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Integer pos = (Integer) holder.checkBox.getTag();
            Toast.makeText(ctx, imageModelArrayList.get(pos).getAnimal() + " clicked!", Toast.LENGTH_SHORT).show();

            if (imageModelArrayList.get(pos).getSelected()) {
                imageModelArrayList.get(pos).setSelected(false);
            } else {
                imageModelArrayList.get(pos).setSelected(true);
            }
        }
    });


}

@Override
public int getItemCount() {
    return imageModelArrayList.size();
}

class MyViewHolder extends RecyclerView.ViewHolder {

    protected CheckBox checkBox;
    private TextView tvAnimal;

    public MyViewHolder(View itemView) {
        super(itemView);

        checkBox = (CheckBox) itemView.findViewById(R.id.cb);
        tvAnimal = (TextView) itemView.findViewById(R.id.animal);
    }

}

}

答案 4 :(得分:8)

只需添加recyclelerview的两个覆盖方法

@Override
public long getItemId(int position) {
return position;
}

@Override
public int getItemViewType(int position) {
return position;
}

答案 5 :(得分:2)

如上所述,对象的检查状态应包含在对象属性中。在某些情况下,您可能还需要通过单击对象本身来更改对象选择状态,并让CheckBox通知其实际状态(选中或未选中)。然后,该复选框将在给定适配器的实际位置(默认情况下(在大多数情况下)为列表中元素的位置)上使用对象的状态。

检查下面的代码段,可能会有用。

import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class TakePicImageAdapter extends RecyclerView.Adapter<TakePicImageAdapter.ViewHolder>{
    private Context context;
    private List<Image> imageList;

    public TakePicImageAdapter(Context context, List<Image> imageList) {
        this.context = context;
        this.imageList = imageList;
    }

    @Override
    public TakePicImageAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(context).inflate(R.layout.image_item,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final TakePicImageAdapter.ViewHolder holder, final int position) {
        File file=new File(imageList.get(position).getPath());
        try {
            Bitmap bitmap= MediaStore.Images.Media.getBitmap(context.getContentResolver(), Uri.fromFile(file));
            holder.image.setImageBitmap(bitmap
            );
        } catch (IOException e) {
            e.printStackTrace();
        }
        holder.selectImage.setOnCheckedChangeListener(null);
        holder.selectImage.setChecked(imageList.get(position).isSelected());
        holder.selectImage.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                holder.selectImage.setChecked(isChecked);
                imageList.get(position).setSelected(isChecked);
            }
        });
        holder.image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (imageList.get(position).isSelected())
                {
                    imageList.get(position).setSelected(false);
                    holder.selectImage.setChecked(false);
                }else
                {
                    imageList.get(position).setSelected(true);
                    holder.selectImage.setChecked(true);
                }
            }
        });

    }

    @Override
    public int getItemCount() {
        return imageList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public ImageView image;public CheckBox selectImage;
        public ViewHolder(View itemView) {
            super(itemView);
            image=(ImageView)itemView.findViewById(R.id.image);
            selectImage=(CheckBox) itemView.findViewById(R.id.ch);

        }
    }
}

答案 6 :(得分:1)

您需要将onBindViewHolder(逻辑)交互与CheckBox分开,并将用户交互与复选框分开。我使用OnCheckedChangeListener进行用户交互(很明显)和ViewHolder.bind()用于逻辑,这就是为什么你需要在设置holder之前将checked侦听器设置为null并且在holder准备就绪之后 - 为用户交互配置已检查的监听器。

boolean[] checkedStatus = new boolean[numberOfRows];

@Override
        public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
        final ViewHolderItem itemHolder = (ViewHolderItem) holder;

        //holder.bind should not trigger onCheckedChanged, it should just update UI
        itemHolder.checkBox.setOnCheckedChangeListener(null);

        itemHolder.bind(position);

        itemHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    checkedStatus[holder.getAdapterPosition()] = true;
                    performCheckedActions(); //your logic here
                } else {
                    checkedStatus[holder.getAdapterPosition()] = false;
                    performUncheckedActions(); //your logic here
                }
            }
        });
    }

public void bind(int position) {
            boolean checked = checkedStatus[position];
            if (checked) {
                checkBox.setChecked(false);
            } else {
                checkBox.setChecked(true);
            }
        }

答案 7 :(得分:1)

我发现这个解决方案的问题是,通过创建静态全局 数组并在“onBindViewHolder”中使用它 ADAPER CLASS,我在其中创建了所需的所有全局变量/对象。

public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder> {
private Context context;
public static class PersonViewHolder extends RecyclerView.ViewHolder {

    CardView cv;
    TextView question,category;
    TextView personAge;
    ImageView upvote;
    Button b1;
    public static int k;
    private int visibleThreshold = 5;
    public static int i=0;
     static int  check[]; //Static array
    PersonViewHolder(View itemView,int i) {
        super(itemView);
        if(i==PersonViewHolder.k)
        {
            b1=(Button)itemView.findViewById(R.id.loadmore);

        }
        else
        {
            cv = (CardView)itemView.findViewById(R.id.cv);
            question = (TextView)itemView.findViewById(R.id.question);
            category = (TextView)itemView.findViewById(R.id.text_categ);
            personAge = (TextView)itemView.findViewById(R.id.text1);
            upvote = (ImageView)itemView.findViewById(R.id.upvote);

        }

    }

}

这里(RVADAPTER CLASS的IN CONSTRUCTOR)我给数组的大小等于我将要在回收者视图中显示的项目的大小/没有

List<Person> persons;

RVAdapter(List<Person> persons){
    this.persons = persons;
    PersonViewHolder.check=new int[persons.size()];
    PersonViewHolder.k=persons.size();
}

BindViewHolder,我,在按钮上应用了这个概念,当我点击按钮时,按钮的背景图像会发生变化。 我使用的按钮的对象是名称为“upvote”,因为“i”保存了Recycler视图中每个项目的位置,我将其用作数组的索引,该数组作为标志工作并且跟踪元素的状态。

@Override
public void onBindViewHolder(final PersonViewHolder personViewHolder, final int i) {
    if(i==PersonViewHolder.k) {
        personViewHolder.b1.setText("load more");

    }
    else
     {
        personViewHolder.question.setText(persons.get(i).name);
        personViewHolder.personAge.setText(persons.get(i).age);

         if(personViewHolder.check[i]==0)
         {personViewHolder.upvote.setBackgroundResource(R.drawable.noupvote);
         }
         else
         {
             personViewHolder.upvote.setBackgroundResource(R.drawable.upvote);

         }

         personViewHolder.upvote.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 if(personViewHolder.check[i]==0)
                 {personViewHolder.check[i]=1;
                     personViewHolder.upvote.setBackgroundResource(R.drawable.upvote);


                 }
                 else
                 {personViewHolder.check[i]=0;
                     personViewHolder.upvote.setBackgroundResource(R.drawable.noupvote);

                 }


             }
         });
        // personViewHolder.personPhoto.setImageResource(persons.get(i).photoId);
    }

}

答案 8 :(得分:1)

使用Kotlin对我来说唯一解决此问题的方法是在设置变量之前清除OnCheckedChangeListener,然后在设置OnCheckedChangeListener之后创建新的checked

我在RecyclerView.ViewHolder

中执行以下操作
task.setOnCheckedChangeListener(null)
task.isChecked = item.status
task.setOnCheckedChangeListener { _: CompoundButton, checked: Boolean ->
    item.status = checked
    ...
    do more stuff
    ...
}

答案 9 :(得分:1)

在我看来,这行得通。

@Override
public void onViewRecycled(MyViewHolder holder) {
    holder.checkbox.setChecked(false); // - this line do the trick
    super.onViewRecycled(holder);
}

答案 10 :(得分:0)

这是一个对我有用的 Kotlin 解决方案

this.cart

答案 11 :(得分:0)

解决方案是选中复选框。需要存储这个单独的列表。并使用该列表填充回收站视图中的复选框。

你可以参考这个链接。

https://blog.oziomaogbe.com/2017/10/18/android-handling-checkbox-state-in-recycler-views.html

答案 12 :(得分:0)

完整示例
公共类ChildAddressAdapter扩展了RecyclerView.Adapter {

private Activity context;
private List<AddressDetail> addressDetailList;
private int selectedPosition = -1;

public ChildAddressAdapter(Activity context, List<AddressDetail> addressDetailList) {
    this.context = context;
    this.addressDetailList = addressDetailList;
}

@NonNull
@Override
public CartViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    LayoutInflater inflater = LayoutInflater.from(context);
    View myView = inflater.inflate(R.layout.address_layout, parent, false);
    return new CartViewHolder(myView);
}

@Override
public void onBindViewHolder(@NonNull CartViewHolder holder, int position) {

    holder.adress_checkbox.setOnClickListener(view -> {
        selectedPosition = holder.getAdapterPosition();
        notifyDataSetChanged();
    });

    if (selectedPosition==position){
        holder.adress_checkbox.setChecked(true);
    }
    else {
        holder.adress_checkbox.setChecked(false);
    }


}

@Override
public int getItemCount() {
    return  addressDetailList.size();
}

class CartViewHolder extends RecyclerView.ViewHolder
{
    TextView address_text,address_tag;
    CheckBox adress_checkbox;

    CartViewHolder(View itemView) {
        super(itemView);
        address_text = itemView.findViewById(R.id.address_text);
        address_tag = itemView.findViewById(R.id.address_tag);
        adress_checkbox = itemView.findViewById(R.id.adress_checkbox);
    }
}

}

答案 13 :(得分:0)

这是由于一次又一次地创建视图,最好的选择是在设置适配器之前清除缓存

recyclerview.setItemViewCacheSize(your array.size());

答案 14 :(得分:0)

setItemViewCacheSize(int size)添加到recyclerview并通过列表的大小解决了我的问题。

mycode:

mrecyclerview.setItemViewCacheSize(mOrderList.size());
mBinding.mrecyclerview.setAdapter(mAdapter);

来源: https://stackoverflow.com/a/46951440/10459907

答案 15 :(得分:0)

使用数组保存项目的状态

在适配器中,使用Map或SparseBooleanArray(与map类似,但它是int和boolean的键值对)将所有项目的状态存储在项目列表中,然后在切换检查状态时使用键和值进行比较

在适配器中创建一个SparseBooleanArray

// sparse boolean array for checking the state of the items

    private SparseBooleanArray itemStateArray= new SparseBooleanArray();

然后在项目点击处理程序onClick()中使用itemStateArray中的项目状态在切换之前进行检查,这是一个示例

        @Override
        public void onClick(View v) {
            int adapterPosition = getAdapterPosition();
            if (!itemStateArray.get(adapterPosition, false)) {
                mCheckedTextView.setChecked(true);
                itemStateArray.put(adapterPosition, true);
            }
            else  {
                mCheckedTextView.setChecked(false);
                itemStateArray.put(adapterPosition, false);
            }
        }

另外,使用稀疏布尔数组设置绑定视图时的检查状态

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    holder.bind(position);
}

@Override
public int getItemCount() {
    if (items == null) {
        return 0;
    }
    return items.size();
}

 void loadItems(List<Model> tournaments) {
    this.items = tournaments;
    notifyDataSetChanged();
}


class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    CheckedTextView mCheckedTextView;

    ViewHolder(View itemView) {
        super(itemView);
        mCheckedTextView = (CheckedTextView) itemView.findViewById(R.id.checked_text_view);
        itemView.setOnClickListener(this);
    }

    void bind(int position) {
        // use the sparse boolean array to check
        if (!itemStateArray.get(position, false)) {
            mCheckedTextView.setChecked(false);}
        else {
            mCheckedTextView.setChecked(true);
        }
    }

最终的适配器将类似于this

答案 16 :(得分:0)

在使用> dat_puremath age traveltime studytime failures famrel freetime goout Dalc Walc health absences Math_G1 Math_G2 Math_G3 Por_G1 Por_G2 Por_G3 DoubleSub 918 15 2 4 0 4 4 2 2 3 3 12 16 16 16 NA NA NA 0 931 16 1 2 3 2 3 3 2 2 4 5 7 7 7 NA NA NA 0 933 16 1 2 0 3 3 4 1 1 4 0 12 13 14 NA NA NA 0 935 16 1 1 0 4 5 2 1 1 5 20 13 12 12 NA NA NA 0 927 16 2 2 0 3 4 4 1 4 5 2 13 13 11 NA NA NA 0 929 17 1 2 0 5 3 3 1 1 3 0 8 8 9 NA NA NA 0 942 17 1 3 0 3 3 2 2 2 3 3 11 11 11 NA NA NA 0 928 16 1 2 0 1 2 2 1 2 1 14 12 13 12 NA NA NA 0 936 17 1 3 0 3 2 3 1 1 4 4 10 9 9 NA NA NA 0 939 17 1 4 0 5 2 2 1 2 5 0 17 17 18 NA NA NA 0 941 17 1 2 0 4 2 2 1 1 3 12 11 9 9 NA NA NA 0 937 17 1 2 0 5 4 5 1 2 5 4 10 9 11 NA NA NA 0 925 16 1 2 0 4 4 2 1 1 3 0 14 14 14 NA NA NA 0 938 17 1 3 0 4 3 3 1 1 3 6 13 12 12 NA NA NA 0 921 15 1 3 0 4 2 2 1 1 5 2 9 11 11 NA NA NA 0 943 17 1 3 0 4 4 3 1 1 5 7 12 14 14 NA NA NA 0 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA.1 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA.2 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA.3 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA.4 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA.5 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA.6 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA.7 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA.8 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA.9 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA.10 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA.11 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA.12 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA.13 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA.14 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA.15 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA.16 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA.17 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA.18 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA.19 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA.20 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA.21 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA.22 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA.23 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA.24 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA.25 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA.26 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA.27 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA.28 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA.29 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA.30 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA.31 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA 而不是setOnCheckedChangeListener时会发生这种情况,而在内部只需执行以下简单操作即可:

setObClickListener
  

注意:在列表模型中,添加一个名称为 if (list.get(position).isCheck()) { list.get(position).setCheck(false); } else { list.get(position).setCheck(true); } 的布尔变量,并为其设置getter和setter,在上述情况下,我的是setCheck和isCheck

希望有帮助的话+投票给这个答案

答案 17 :(得分:0)

public class TagYourDiseaseAdapter扩展了RecyclerView.Adapter {     private ReCyclerViewItemClickListener mRecyclerViewItemClickListener;     private Context mContext;

List<Datum> deviceList = Collections.emptyList();

/**
 * Initialize the values
 *
 * @param context : context reference
 * @param devices : data
 */

public TagYourDiseaseAdapter(Context context, List<Datum> devices,
                             ReCyclerViewItemClickListener mreCyclerViewItemClickListener) {
    this.mContext = context;
    this.deviceList = devices;
    this.mRecyclerViewItemClickListener = mreCyclerViewItemClickListener;
}


/**
 * @param parent   : parent ViewPgroup
 * @param viewType : viewType
 * @return ViewHolder
 * <p>
 * Inflate the Views
 * Create the each views and Hold for Reuse
 */
@Override
public TagYourDiseaseAdapter.OrderHistoryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_tag_disease, parent, false);
    TagYourDiseaseAdapter.OrderHistoryViewHolder myViewHolder = new TagYourDiseaseAdapter.OrderHistoryViewHolder(view);
    return myViewHolder;
}


/**
 * @param holder   :view Holder
 * @param position : position of each Row
 *                 set the values to the views
 */
@Override
public void onBindViewHolder(final TagYourDiseaseAdapter.OrderHistoryViewHolder holder, final int position) {
    Picasso.with(mContext).load(deviceList.get(position).getIconUrl()).into(holder.document);
    holder.name.setText(deviceList.get(position).getDiseaseName());

    holder.radioButton.setOnCheckedChangeListener(null);
    holder.radioButton.setChecked(deviceList.get(position).isChecked());

    //if true, your checkbox will be selected, else unselected
    //holder.radioButton.setChecked(objIncome.isSelected());

    holder.radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            deviceList.get(position).setChecked(isChecked);
        }
    });


}

@Override
public int getItemCount() {
    return deviceList.size();
}


/**
 * Create The view First Time and hold for reuse
 * View Holder for Create and Hold the view for ReUse the views instead of create again
 * Initialize the views
 */

public class OrderHistoryViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    ImageView document;
    TextView name;
    CheckBox radioButton;

    public OrderHistoryViewHolder(View itemView) {
        super(itemView);
        document = itemView.findViewById(R.id.img_tag);
        name = itemView.findViewById(R.id.text_tag_name);
        radioButton = itemView.findViewById(R.id.rdBtn_tag_disease);
        radioButton.setOnClickListener(this);
        //this.setIsRecyclable(false);
    }


    @Override
    public void onClick(View view) {
        mRecyclerViewItemClickListener.onItemClickListener(this.getAdapterPosition(), view);
    }
}

}

答案 18 :(得分:0)

好的有很多答案这里我会发布我的代码,我会简单解释一下我做了什么......也许可以帮助像我这样的小辈:D。

1-目标:

我们将创建一个包含RecyclerViewCheckBox的{​​{1}}列表,如下所示:

enter image description here 2-模型类

RadioButton

3-My Amazing Adapter

public class ModelClass {
private String time;
private boolean checked;
private boolean free;
private boolean paid;

public TherapistScheduleModel(String time, boolean checked, boolean free, boolean paid) {
    this.time = time;
    this.checked = checked;
    this.free = free;
    this.paid = paid;
}

public boolean isFree() {
    return free;
}

public void setFree(boolean free) {
    this.free = free;
}

public boolean isPaid() {
    return paid;
}

public void setPaid(boolean paid) {
    this.paid = paid;
}

public String getTime() {
    return time;
}

public void setTime(String time) {
    this.time = time;
}

public boolean getChecked() {
    return checked;
}

public void setChecked(boolean checked) {
    this.checked= checked;
}
}

3-在活动中,您可以获得以下内容:

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private Context context;
private ListAllListeners listAllListeners;
private ArrayList<ModelClass> mDataList;

public MyAdapter(Context context, ArrayList<ModelClass> mDataList,
                             ListAllListeners listAllListeners) {
    this.mDataList = mDataList;
    this.listAllListeners = listAllListeners;
    this.context = context;
}

@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View view = inflater.inflate(R.layout.single_view, parent, false);
    return new MyViewHolder(view);
}

@Override
public int getItemCount() {
    if (mDataList != null)
        return mDataList.size();
    else
        return 0;
}

@Override
public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) {
     //important to:
    //setOnCheckedChangeListener to 'null'
    holder.checkBoxTime.setOnCheckedChangeListener(null);
    holder.freeRB.setOnCheckedChangeListener(null);
    holder.paidRB.setOnCheckedChangeListener(null);

    //Check Box
            holder.checkBoxTime.setText(mDataList.get(holder.getAdapterPosition()).getTime());
    //here we check if the item is checked or not from the model.
    if(mDataList.get(holder.getAdapterPosition()).getChecked())
        holder.checkBoxTime.setChecked(true);
    else
        holder.checkBoxTime.setChecked(false);

    holder.checkBoxTime.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if (b) {
                mDataList.get(holder.getAdapterPosition()).setChecked(true);
                listAllListeners.onItemCheck(holder.checkBoxTime.getText().toString(), holder.getAdapterPosition());
            }
            else {
                mDataList.get(holder.getAdapterPosition()).setChecked(false);
                listAllListeners.onItemUncheck(holder.checkBoxTime.getText().toString(), holder.getAdapterPosition());
            }
        }
    });

    //Radio Buttons

    if(mDataList.get(holder.getAdapterPosition()).isFree())
        holder.freeRB.setChecked(true);
    else
        holder.freeRB.setChecked(false);
    holder.freeRB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if (b) {
                mDataList.get(holder.getAdapterPosition()).setFree(true);
                listAllListeners.onFreeCheck(holder.freeRB.getText().toString(), holder.getAdapterPosition());
            } else {
                mDataList.get(holder.getAdapterPosition()).setFree(false);
                listAllListeners.onFreeUncheck(holder.freeRB.getText().toString(), holder.getAdapterPosition());
            }
        }
    });

   //***and so on to paidRB***

}//end onBindViewHolder()

public interface ListAllListeners {
//here is a list of clicked listeners to use them as you want ;).
//you can get a list of checked or unChecked of all 
        void onItemCheck(String checkBoxName, int position);
        void onItemUncheck(String checkBoxName, int position);
        void onFreeCheck(String name, int pos);
        void onFreeUncheck(String name, int pos);
        void onPaidCheck(String name, int pos);
        void onPaidUncheck(String name, int pos);
    }

    class MyViewHolder extends RecyclerView.ViewHolder {

        CheckBox checkBoxTime;
        RadioButton freeRB, paidRB;

        MyViewHolder(View itemView) {
            super(itemView);
            checkBoxTime = itemView.findViewById(R.id.timeCheckBox);
            freeRB = itemView.findViewById(R.id.freeRadioBtn);
            paidRB = itemView.findViewById(R.id.paidRadioBtn);
        }
    }//end class MyViewHolder

    }//end class

答案 19 :(得分:0)

我遇到了同样的问题。当我点击我的recyclerView中的项目切换按钮时,每10个项目中都会出现一个切换按钮(例如,如果点击了0索引的项目,那么9,18,27个索引的项目也会被点击)。首先,我在onBindViewHolder中的代码是:

if (newsItems.get(position).getBookmark() == 1) {
            holder.getToggleButtonBookmark().setChecked(true);
        }

但后来我添加了Else声明

if (newsItems.get(position).getBookmark() == 1) {
            holder.getToggleButtonBookmark().setChecked(true);
//else statement prevents auto toggling
        } else{
            holder.getToggleButtonBookmark().setChecked(false);
        }

问题解决了

答案 20 :(得分:0)

我在带有开关的RecyclerView列表中遇到了同样的问题,并使用@oguzhand回答解决了问题,但是在checkedChangeListener中使用了这段代码:

if (buttonView.isPressed()) {
    if (isChecked) {
        group.setSelected(true);
    } else {
        group.setSelected(false);
    }
}else{
    if (isChecked) {
        buttonView.setChecked(false);
    } else {
        buttonView.setChecked(true);
    }
}

(其中&#39; group&#39;是我想要选择/取消选择的实体)

答案 21 :(得分:-1)

对我来说有用的是在视图将被回收(onViewRecycled)时取消viewHolder上的侦听器:

 override fun onViewRecycled(holder: AttendeeViewHolder) {
            super.onViewRecycled(holder)
            holder.itemView.hasArrived.setOnCheckedChangeListener(null);
            holder.itemView.edit.setOnClickListener { null }
        }

答案 22 :(得分:-1)

我建议不要在checkBox.setOnCheckedChangeListener中使用recyclerViewAdapter。因为在滚动recyclelerView时,适配器将触发checkBox.setOnCheckedChangeListener不安全。相反,使用checkBox.setOnClickListener与用户输入进行交互。

例如:

     public void onBindViewHolder(final ViewHolder holder, int position) {
        /*
         .
         .
         .
         .
         .
         .
        */

        holder.checkBoxAdapterTasks.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isChecked =  holder.checkBoxAdapterTasks.isChecked();
                if(isChecked){
                    //checkBox clicked and checked
                }else{
                    //checkBox clicked and unchecked
                }

            }
        });

    }