Android toggleButton.setOnText and .invalidate doesn't refresh text
Asked Answered
V

1

6

I have a method like this:

ToggleButton toggle = ((ToggleButton)findViewById(R.id.toggle));
toggle.setTextOn("blah");
toggle.setTextOff("blahblah");
toggle.invalidate(); // doesn't work?

This methods gets called from onOptionsItemSelected. The toggle button is inside a LinearLayout which is inside another LinearLayout.

I'm expecting the text to update as soon as the method is called. Rather the text on the toggle only updates after I manually press it to switch states. What am I missing here, am I using the wrong method? Why doesn't .invalidate work?

Vicegerent answered 17/1, 2015 at 12:50 Comment(0)
C
12

Instead of invalidating, you can update the button like this:

toggle.setChecked(toggle.isChecked());

Update:

It is weird that setTextOff and setTextOn don't update the button. However setText does that. So just set the text for each button states and setText to update current value:

// Text based on state
ToggleButton toggle = ((ToggleButton)findViewById(R.id.toggle));
toggle.setTextOn("blah");
toggle.setTextOff("blahblah");

CharSequence text = toggle.isChecked() ? toggle.getTextOn() : toggle.getTextOff();
toggle.setText(text);
Caducous answered 17/1, 2015 at 13:7 Comment(3)
This works, but why? And is this really the best way to do it?Vicegerent
the solutions feel very hacky but they work. Thanks!Vicegerent
help, neither of those work for me! the text is setted but the toggle is not updated!!Jegger

© 2022 - 2024 — McMap. All rights reserved.