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.
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.
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.
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
}
};
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With