It is possible to create a ToggleButton without text?

Pableras84 picture Pableras84 · Jul 23, 2012 · Viewed 22.9k times · Source

i want to create a android default ToggleButton like this: enter image description here

but i want to create it without TEXT

I tryed with this code:

ToggleButton tb = new ToggleButton(map);
tb.setText(null);
tb.setTextOn(null);
tb.setTextOff(null);

But it is leaving a empty space in the top of the horizontal green bar.

I dont want that empty space, i only want the horizontal green bar.

How to achieve it?

thanks

Answer

SteveR picture SteveR · Jul 23, 2012

The empty space in the top is caused by the 2 Ninepatch (btn_toggle_off.9.png and btn_toggle_on.9.png ) used in default toggleButton style.

To perfectly center the horizontal bar, you must create a new style for ToggleButton that will use two new ninepatch derived form original.

Edit: Method requiring minimal XML:

  • create your two ninepatches for your togglebutton, name it: my_btn_toggle_on and my_btn_toggle_off

  • in drawable folder, create my_btn_toggle.xml:

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_checked="false" android:drawable="@drawable/my_btn_toggle_off" />
        <item android:state_checked="true" android:drawable="@drawable/my_btn_toggle_on" />
    </selector>
    
  • in your code, add tb.setBackgroundResource(R.drawable.my_btn_toggle) :

    ToggleButton tb = new ToggleButton(map);
    tb.setText(null);
    tb.setTextOn(null);
    tb.setTextOff(null);
    tb.setBackgroundResource(R.drawable.my_btn_toggle)