Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Checkbox listener method is called right after the screen rotation

I'm starting to program android app and I'm having a problem with a checkbox.

I've got a checkbox in my activity, i put a log message in the OnCheckedChanged method to be launched when the checkbox is checked, but when I rotate the screen the message appears again as if the OnCheckedChanged method was call automatically when the system destroys and creates the activity again.

What is happening?? thanks.

like image 950
Juan Pablo Alvarez Ovalle Avatar asked Jul 05 '13 17:07

Juan Pablo Alvarez Ovalle


People also ask

How to use CheckBox in android?

When the user selects a checkbox, the CheckBox object receives an on-click event. To define the click event handler for a checkbox, add the android:onClick attribute to the <CheckBox> element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event.

How to set CheckBox checked in android programmatically?

By default, the android CheckBox will be in the OFF (Unchecked) state. We can change the default state of CheckBox by using android:checked attribute. In case, if we want to change the state of CheckBox to ON (Checked), then we need to set android:checked = “true” in our XML layout file.


2 Answers

The best and cleanest solution I have used multiple times is to check if View.isPressed(). This makes sense since the user will be pressing on the Switch when it triggers the callback.

private Switch.OnCheckedChangeListener mOnSwitch = new Switch.OnCheckedChangeListener()
{
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
    {
        if (!buttonView.isPressed())
        {
            // Not from user!
            return;
        }

        // Handle user check change
    }
};
like image 89
Jona Avatar answered Sep 28 '22 05:09

Jona


I have been gone through such problem once. it was so frustrating finally i remove OnCheckedChangedListener and replace it with onClickListener. In onclick methode i use c.IsChecked().

My guess is that android call onCheckChange whenever checkbox state is changed either by user of through code (by c.setchecked(boolean)),

In your case c.setchecked(boolean) methode called internally by android to restore UI state.

Hope it will help.

like image 20
Mufazzal Avatar answered Sep 28 '22 06:09

Mufazzal