How to change ToggleButton state programmatically?

Franco picture Franco · May 9, 2011 · Viewed 44.5k times · Source

I have a ToggleButton defined like this:

<ToggleButton android:text="ToggleButton" android:id="@+id/toggle"
    android:layout_height="wrap_content" android:layout_width="fill_parent"></ToggleButton>

And I want to change its state programmatically. I tried using the setChecked and toggle methods, but neither of those works in my situation.

I have an ongoing notification and when my activity receives the notification intent, the toggle button should be set to not checked, but it's not working.

I'm doing this on the activity's onResume. The code is being executed but the ToggleButton's state doesn't change.

Weirdly, if I call setChecked(false) on the activity's onCreate it does changes the button's state, but not on onResume. What am I missing?

Thanks.

Answer

Franco picture Franco · May 10, 2011

Got it. Kind of.

I had this

    protected void onResume() {
        super.onResume();

        Intent intent;

        if ((intent = getIntent()) != null && MainActivity.STOP.equals(intent.getAction())) {
            disable();

            toggle.setChecked(false);

            finish();
        }
    }

But the call to finish wasn't actually doing anything. I removed it and now it works. Not a clue why this fixed it.

Someone care to explain?