Android Switch Compat State Issue

2.2k views Asked by At

UI Sample

I want to change the state of child switches from parent switch.

in brief:

case 1: Parent on -> all Child switches on

case 2: Parent off -> all Child switches off

case 3: Child 2 off (Child 1 & 3 ON) -> Parent On

Issue When i on/off all child switches Parent switch should on/off accordingly.

below is my code in code case 1,2 & 3 working fine.

switchParent.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

            if (b) {

                switchChild1.setChecked(true);
                switchChild2.setChecked(true);
                switchChild3.setChecked(true);

            } else {

                switchChild1.setChecked(false);
                switchChild2.setChecked(false);
                switchChild3.setChecked(false);

            }
        }
    }); switchChild1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            setState();
        }
    });

    switchChild2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            setState();
        }
    });


    switchChild3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            setState();
        }
    });

setState()

private void setState() {

   if (switchChild1.isChecked() || switchChild2.isChecked() || switchChild3.isChecked()) {

        switchParent.setChecked(true);

    } else {

        switchParent.setChecked(false);

    }

}

I will appreciate any help.

1

There are 1 answers

1
Jigar Shekh On

Change your setState() method.

private void setState() {
if (switchChild1.isChecked() && switchChild2.isChecked() && switchChild3.isChecked()) {
    switchParent.setChecked(true);
} else {
    switchParent.setChecked(false);
}

}