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.

Upvotes: 7

Views: 3037

Answers (4)

Jona
Jona

Reputation: 13555

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
    }
};

Upvotes: 11

madrinja
madrinja

Reputation: 1

Actually, as somebody already mentioned, it is possible to detect who launched the 'change of state' event by using isPressed method, i.e. it responds only to user action.
However there is a problem with Switch control which, apart from clicking, can also be dragged left or right which also changes the state but isPressed method doesn't detect that. I was hoping to find in the Switch class a method perhaps called isDragged, but there is nothing.

It's sort of hard to believe that they forgot to implement such a thing so probably I'm missing something.

Upvotes: 0

Mr_Hmp
Mr_Hmp

Reputation: 2535

Try adding following lines in your manifest file in application tag:

<activity android:name="MainActivity" android:configChanges="keyboardHidden|orientation">

also read this , this will solve your problem.

Upvotes: -4

Mufazzal
Mufazzal

Reputation: 883

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.

Upvotes: 8

Related Questions