How to check toggle button is on or off in android

Set isChecked() function on toggle button to access start stop values.

With the use of isChecked() function on toggle button you can access toggle button on off values to perform various tasks on toggle button on event and toggle button off event. You can also display a toast message whether button is off or on. So here is the complete step by step tutorial for How to check toggle button is on or off in android.

android-project-download-code-button

How to check toggle button is on or off in android.

Code for MainActivity.java file.

 package com.android_examples.com.checktogglebuttononoff;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends Activity {

 ToggleButton Tbutton;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 Tbutton = (ToggleButton)findViewById(R.id.toggleButton1);
 Tbutton.setOnClickListener(new View.OnClickListener() {
 
 @Override
 public void onClick(View v) {
 
 if(Tbutton.isChecked())
 {
 Toast.makeText(MainActivity.this, "Toggle button is on", Toast.LENGTH_LONG).show();
 }
 else {
 Toast.makeText(MainActivity.this, "Toggle button is Off", Toast.LENGTH_LONG).show();
 }
 }
 });
 }
}

Code for activity_main.xml layout file.

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.android_examples.com.checktogglebuttononoff.MainActivity" >

 <ToggleButton
 android:id="@+id/toggleButton1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignParentTop="true"
 android:layout_centerHorizontal="true"
 android:layout_marginTop="101dp"
 android:text="ToggleButton" />

</RelativeLayout>

Screenshot:

How to check toggle button is on or off in android toggle button off

Click Here To Download toggle button is on or off in android project.

Leave a Reply

Your email address will not be published. Required fields are marked *