Android UI How to - Use ToggleButton








The ToggleButton control is a two-state button. It can be in either the On or Off state.

By default ToggleButton sets the button's text to On when it's in the On state and Off when it's in the Off state.

You can modify the text for the ToggleButton if On/Off is not appropriate for your application.

The following code sets the button's On/Off text to Stop and Run by using android:textOn and android:textOff properties.

<ToggleButton android:id="@+id/cctglBtn"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="Toggle Button"
              android:textOn="Stop"
              android:textOff="Run"/>

Because ToggleButtons have on and off text as separate attributes, the android:text attribute of a ToggleButton is not really used.





Example

XML layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
/*from   www. j  a va 2s  .c om*/
    <ToggleButton android:id="@+id/cctglBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Toggle Button"
        android:textOn="Stop"
        android:textOff="Run"/>
</LinearLayout>

Java code

package com.java2s.app;
// w  w  w .  j a v  a 2 s  . co m
import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

}
null