How to change ToggleButton state programmatically?
I have a ToggleButton defined like this:
<ToggleButton android:text="ToggleButton" android:id="@+id/toggle"
android:layout_height="wrap_content" android:layout_width="fi开发者_StackOverflowll_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.
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?
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
?
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.....
I was having the same issue. I fixed it by calling ToggleButton#isChecked() method before setting the state.
if (mToggleSwitch.isChecked()) {
mToggleSwitch.setChecked(false);
}
精彩评论