Checkbox condition isChecked

Asked

Viewed 831 times

2

Hello, I am using a Checkbox and I would like that if it was Checked, it becomes visible a Layout. I’m using the code below and it only works for when it is clicked, but I already want to leave it checked. I tried to get the code out of the . setOnCheckedChangeListener, but it didn’t work. Does anyone know what might be going on? 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);


                }
            }
        });

2 answers

3

You need to already set it as checked, even before the Changelistener

Example:

cbx22.setSelected(true);

By the time he gets on the Changelistener he’ll be checked out

  • Hi I’m already setting it checked, but then it doesn’t work. Still, I have to uncheck and check again.

2


The Istener will not be called if the CheckBox has been checked before setting the Switch. You are probably checking inside the layout with android:checked="true". Use android:checked="false" in the layout and after defining the Istener, 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, so in the layout initialize as true and in Activity after Istener, setChecked(false).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.