How to change ToggleButton state programmatically?
Asked Answered
A

4

13

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.

Amphithecium answered 9/5, 2011 at 21:44 Comment(0)
A
19

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?

Amphithecium answered 10/5, 2011 at 0:41 Comment(0)
A
2

It should work.

Check that you don't have a call to setChecked(true) somewhere else in the code that is executed after you set it to false. Perhaps inside an OnCheckedChangeListener?

Accompanyist answered 9/5, 2011 at 21:52 Comment(1)
I know it should, but it doesn't. I don't have any other calls to setChecked, just searched through all the code.Amphithecium
O
1

Call Finish when your activity is done and should be closed. The ActivityResult is propagated back to whoever launched you via onActivityResult().

So in your case Instead of changing the toggle Button state it goes back to its calling method which may be the onCreate() or onPause...

Details about using finish here.....

Obstetric answered 2/5, 2013 at 8:2 Comment(0)
A
1

I was having the same issue. I fixed it by calling ToggleButton#isChecked() method before setting the state.

if (mToggleSwitch.isChecked()) {
    mToggleSwitch.setChecked(false);
}
Aerospace answered 17/12, 2019 at 7:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.