当我在Android中取消选择甚至1个复选框时,如何取消选择全选复选框

时间:2018-11-15 06:05:10

标签: java android listview checkbox

我想要项目中的功能,其中单击“全选”复选框,必须选中列表中的所有复选框,而取消选中该复选框,则必须取消选中所有其他复选框。我通过执行以下操作来实现此功能:

/*in my main activity i have done this*/

  cbSelectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                for (int i = 0; i < resumeSearchList.size(); i++) {
                    resumeSearchList.get(i).setSelected(cbSelectAll.isChecked());
                }
                cvSearchResultListAdapter.notifyDataSetChanged();
            }
        });
    }

在适配器类中,我已经做到了。

holder.cbSelect.setChecked(dataList.get(position).isSelected());

现在,我的问题是,每当我取消选中列表中的任何复选框时,都必须取消选中“全选”按钮。请帮助

预先感谢

1 个答案:

答案 0 :(得分:1)

您可以在适配器的OnCheckedChangeListener上设置holder.cbSelect.

holder.cbSelect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    dataList.get(holder.getAdapterPosition()).setSelected(isChecked);
                    // here you can call listener to get notified 
            }
        });
    }

您可以让listener在您的Activity.中得到通知

要添加侦听器,

1。创建一个interface

public interface OnMyCheckBoxCheckedChangeListener {
    void onMyCheckBoxCheckedChange();
}

2。在适配器的构造函数中添加参数:

private OnMyCheckBoxCheckedChangeListener mOnMyCheckBoxCheckedChangeListener;

    public YourAdapter(..., ..., OnMyCheckBoxCheckedChangeListener onMyCheckBoxCheckedChangeListener) {
            mOnMyCheckBoxCheckedChangeListener = onMyCheckBoxCheckedChangeListener;
        }

3。您要通知的呼叫界面:

holder.cbSelect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    dataList.get(holder.getAdapterPosition()).setSelected(isChecked);
                    mOnMyCheckBoxCheckedChangeListener.onMyCheckBoxCheckedChange(); 
            }
        });
    }

4。根据您的活动设置适配器:

yourRecyclerView.setAdapter(new YourAdapter(..., ..., new OnMyCheckBoxCheckedChangeListener() {
    @Override
    public void onMyCheckBoxCheckedChange() {
        // you will get notified here.
    }
}));