A ToggleButton widget changes size when the checked state is toggled. For example, if the textOn value is “true” and the textOff value is “not sure call me later”, a checked state toggle causes the button width to change dramatically.
It would be nice to set the width of a ToggleButton to the maximum of the two content-wrapped widths created by textOn and textOff.
Is there a preferred way to maintain constant ToggleButton width? Is the best way to simply call getWidth(), then toggle(), then getWidth() again?
Because its a button with just two strings, there is no harm in providing the width in the XML itself according to the larger string.
But if you want to calculate the width of the strings, it’s simple:
This gives you the width of the string it would take on the screen. Now set the width of the toggle button via
LayoutParams.Lets say parent layout of your toggle button is LinearLayout.
so it should go like:
toggleButton.setLayoutParams(new LayoutParams(WIDTH_YOU_CALCULATED, LinearLayout.LayoutParams.WRAP_CONTENT));
This will set the width and height of your ToggleButton to what you calculated.