[UPDATE]基于主开关的拨动开关

时间:2018-10-26 15:08:21

标签: android recycler-adapter android-togglebutton

我的活动包含一个RecyclerView.Adapter,并且此适配器的每个单元格都包含一个开关。 在我的活动中,我有一个主开关,它将控制适配器中这些开关的行为。

我的主开关:

switchAllBureau.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean b) {
                //code to control adapter switches
            }
        });

适配器代码:

public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) {
        final String nameBureau = bureaus.get(position).getName();

        holder.txtNameBureau.setText(nameBureau);
        holder.switchBureau.setChecked(interactor.isBureauSubscribed(bureaus.get(position).getCode()));
        holder.switchBureau.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean b) {
                if(b){
                    //do something
                } else {
                    //do something
                }
            }
        });
    }

ViewHolder代码:

class MyViewHolder extends RecyclerView.ViewHolder {
    private TextView txtNameBureau;
    private ToggleButton switchBureau;

    MyViewHolder(View view) {
        super(view);
        txtNameBureau = view.findViewById(R.id.txt_name_bureau);
        switchBureau = view.findViewById(R.id.switch_bureau);
    }
}

如何基于主开关更改适配器开关?

更新: 添加私有接口并在创建视图持有人时实现。但是只有最后一个被更新:

private interface ChangeSwitch{
    void change(boolean select);
}

MyViewHolder(View view) {
            super(view);
            txtNameBureau = view.findViewById(R.id.txt_name_bureau);
            switchBureau = view.findViewById(R.id.switch_bureau);
            changeSwitch = new ChangeSwitch() {
                @Override
                public void change(boolean select) {
                    switchBureau.setChecked(select);
                }
            };
        }

在活动的主开关中,我称之为:

public void selectAllBureaus(boolean selectAll){
        changeSwitch.change(selectAll);
    }

0 个答案:

没有答案