复选框也单击选中其他复选框

时间:2019-07-13 07:22:09

标签: java android

当我单击我的第一个第二和第三个复选框时,它还会选中最后三个复选框吗?

这是我的适配器:

@Override
public void onBindViewHolder(@NonNull final NewGamePlayerViewHolder holder, int position) {
    final NewGamePlayerItem currentItem = mNewGamePlayerList.get(position);

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

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

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

    holder.mName.setText(currentItem.getmText());
}

这是项目:

package com.example.frisbeecaddy;

public class NewGamePlayerItem {
    private boolean mCheckBox;
    private String mText;

    public NewGamePlayerItem(boolean checkBox, String text) {
        mCheckBox = checkBox;
        mText = text;
    }

    public boolean getCheckBox() {
        return mCheckBox;
    }

    public String getmText() {
        return mText;
    }
}

这是从这里复制的: CheckBox in RecyclerView keeps on checking different items

但是对我来说isSelected()和setSelected()却说:无法解析方法...

1 个答案:

答案 0 :(得分:0)

首先,您需要记住RecyclerView的核心含义,这就是所有内容的总和(请参见RecyclerView glossary of terms):

  

回收(视图):先前用于显示特定适配器位置的数据的视图可以放置在缓存中,以供以后重用以稍后再次显示相同类型的数据。通过跳过初始的布局膨胀或构造,可以大大提高性能。

因此,您的第一个问题是:

  

当我单击第一个第二和第三个复选框时,它还会选中最后三个复选框

表示您的RecyclerView项目已在另一个项目中重复使用。为了解决该问题,您需要添加机制以保留每个项目的检查状态。您可以通过使用SparseBooleanArray或将对象修改为具有状态变量来实现。

第二问题:

  

但是对我来说isSelected()和setSelected()却说:无法解析方法...

是因为以下代码:

final NewGamePlayerItem currentItem = mNewGamePlayerList.get(position);

...

//set your object's last status
currentItem.setSelected(isChecked);

您尝试在NewGamePlayerItem中调用不存在的方法的位置。

您需要将您的对象修改为如下所示:

package com.example.frisbeecaddy;

public class NewGamePlayerItem {
    private boolean mCheckBox;
    private String mText;
    private boolean mIsSelected;

    public NewGamePlayerItem(boolean checkBox, String text, boolean isSelected) {
        mCheckBox = checkBox;
        mText = text;
        mIsSelected = isSelected;
    }

    public boolean getCheckBox() {
        return mCheckBox;
    }

    public String getmText() {
        return mText;
    }


    // the added methods here
    public boolean isSelected() {
       return mIsSelected;
    }

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