Checkbox condition isChecked

2

Hello, I'm using a CheckBox and I would like it if it was Checked, it becomes visible a Layout. I'm using the code below and it only works for when it's clicked, but I already want to check it out. I tried to get the code from within the .setOnCheckedChangeListener, but it did not work. Does anyone know what might be happening? Thank you

cbx22.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (cbx22.isChecked()) {
                    layhorario.setVisibility(View.VISIBLE);
                } else {
                    layhorario.setVisibility(View.GONE);


                }
            }
        });
    
asked by anonymous 23.11.2016 / 20:09

2 answers

2

The listener will not be called if CheckBox was checked before defining the listener. You're probably checking inside the layout with android:checked="true" . Use android:checked="false" in the layout and after defining the listener, check as true :

cbx22.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (cbx22.isChecked()) {
            layhorario.setVisibility(View.VISIBLE);
        } else {
            layhorario.setVisibility(View.GONE);
        }
    }
});
cbx22.setChecked(true);

Note that the listener is only called when the state changes. If you need the CheckBox initially false, then in the layout start as true and in the activity after the listener, setChecked(false) .

    
25.01.2017 / 14:29
3

You need to set it already checked, even before the ChangeListener

Example:

cbx22.setSelected(true);

When it enters ChangeListener it will already be checked

    
23.11.2016 / 20:17