Android Toggle Button/Switch Tutorial – How To work Toggle Button/Switch Example

By | April 14, 2019

What is ToggleButton

Toggle Button is allow to user change setting between two States.ToggleButton add to layout of basic toggle butto objects. ToggleButton two state of Checked or Unchecked work.
Android 4.0 (API level 14) introduces another kind of toggle button called a switch that provides a slider control, which you can add with a Switch object.  SwitchCompact is a version of the Switch widget which runs on devices back to API 7.

If you need to change button state listener you can use to
CompoundButton.setChecked() or CompoundButton.toggle() method.

ToggleButton Attribute

android:textOn

textOn Attribute is a checked state of ToggleButton worked.

android:textOff

textOff Attribute is a unchecked state of ToggleButton Worked.

Implemetation Of ToggleButton

Create activity_main.xml File and Write the following code.

Now Create MainActivity.java file and write the following code

Now above the code is create one TextView and ToggleButton in xml file and implement CheckedChange Listener in toggle button to MainActivity.java file.CheckedChange Listener is a check of toggle button on ane off to boolean variable isChecked. i have implement if condition ane then check isChecked then textview visible and settext “Vibrate On” And isChecked is false means it is called else part to change textview in “Vibrate Off”.

What is Switch ?

A Switch is a two-state toggle switch widget that can select between two options. The user may drag the “thumb” back and forth to choose the selected option, or simply tap to toggle as if it were a checkbox.Switch is text property of On Off Control.

Implementation Of Switch

Now Create New activity_main.xml File And Following Code

Now Create MainActivity.java File And Following Code

In this above code i have Create one Switch And TextView And Implementation Click Listener in switch and check condition is true or false it means Switch is checked or unchecked and perform visiblity textview and change text in condition is true.