Android Widget – ToggleButton

In Android, the “android.widget.ToggleButton” is a special class to render a button which has only two states, for example,
“on” and “off”. It’s best alternative to radio buttons to turn on or turn off a function.

In this tutorial, we show you how to use XML to create two toggle buttons and a normal button, when user click on the normal button,
it will display the current state of both toggle buttons.

Open “your.xml” file, just add add two “ToggleButton” and a normal button, inside the LinearLayout.

<!--?xml version="1.0" encoding="utf-8"?-->
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical">
    <togglebutton android:id="@+id/toggleButton1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ToggleButton">
    <togglebutton android:id="@+id/toggleButton2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:texton="@string/toggle_turn_on" android:textoff="@string/toggle_turn_off" android:checked="true">
    <button android:id="@+id/btnDisplay" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/btn_display">
//Review the "togglebutton2", we did customized the togglebutton2's display text on and off and made it checked by default.</button></togglebutton></togglebutton></linearlayout>

Inside activity “onCreate()” method, attach a click listeners on a normal button, to display the current state of the toggle button.

public class MainActivity extends Activity {
  private ToggleButton toggleButton1, toggleButton2;
  private Button btnDisplay;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    addListenerOnButton();
  }
  public void addListenerOnButton() {
    toggleButton1 = (ToggleButton) findViewById(R.id.toggleButton1);
    toggleButton2 = (ToggleButton) findViewById(R.id.toggleButton2);
    btnDisplay = (Button) findViewById(R.id.btnDisplay);
    btnDisplay.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
           StringBuffer result = new StringBuffer();
           result.append("toggleButton1 : ").append(toggleButton1.getText());
           result.append("\ntoggleButton2 : ").append(toggleButton2.getText());
           Toast.makeText(MyAndroidAppActivity.this, result.toString(),
            Toast.LENGTH_SHORT).show();
        }
    });
  }
}