Android ToggleButton

Android ToggleButton Example. Android Toggle Button can be used to display checked/unchecked (On/Off) state on the button. It is beneficial if user have to change the setting between two states.

Step 1: Create a new project with name toggleexample and package name com.myexample.mytoggle. Select File -> New -> New Project. Fill the forms and click “Finish” button.

Step 2: Open res -> layout -> xml (or) main.xml and add following code. Here we will create a ToggleButton and a TextView in a RelativeLayout.

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:app="http://schemas.android.com/apk/res-auto"
	xmlns:tools="http://schemas.android.com/tools"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:padding="16dp"
	tools:context=".MainActivity"
	android:background="#FFFFFF">

	<ToggleButton
		android:id="@+id/toggleButton"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_centerHorizontal="true"
		android:layout_centerVertical="true"
		android:onClick="onToggleClick"/>

	<TextView
		android:id="@+id/textView"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_marginBottom="100dp"
		android:layout_centerVertical="true"
		android:layout_centerHorizontal="true"
		android:layout_above="@+id/toggleButton"
		android:textStyle="bold"
		android:textColor="#000000"/>

</RelativeLayout>

Step 3: Open app -> java -> package and open MainActivity.java. Add following code in it. Here when the ToggleButton is clicked, we will display if the Toggle is on or off in a TextView.

package com.myexample.mytoggle;

import android.app.Activity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.ToggleButton; 
import android.widget.TextView;


public class MainActivity extends Activity {
	
	ToggleButton toggleButton;
	TextView textView;
	
    @Override 
	protected void onCreate(Bundle savedInstanceState) { 
	    super.onCreate(savedInstanceState); 
	    setContentView(R.layout.main); 
		
		toggleButton = (ToggleButton) findViewById(R.id.toggleButton);	
		textView = (TextView) findViewById(R.id.textView); 
		
		}
		
	public void onToggleClick(View view){ 
		if(toggleButton.isChecked()){ 
			textView.setText("Toggle is ON"); 
			} 
		else{ 
			textView.setText("Toggle is OFF"); 
			} 
		} 
}

Output:

Now run the app. When you switch on the ToggleButton, it will display ‘Toggle is ON’, and when you switch it off it will display ‘Toggle is OFF’.