Android ToggleButton control example

Android ToggleButton is a facility that we can display the ON / OFF state of a button. This property will be useful if we are developing applications to control Bluetooth,WiFi etc , to change the state of device between ON and OFF.

For implementing a basic toggle button you just need to add the following code to your layout file

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

Suppose if you want to change the text in the button in ON/OFF states , you can add the following lines to the above code

android:textOn="ON--text"
android:textOff="OFF--text"

Full code will be

<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ToggleButton"
android:textOn="ON--text"
android:textOff="OFF--text"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />

Now if you want the state of the togglebutton in any action , you can use the below code

First you need to get reference of toggle in class file

ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);

Now use the below code in your action like Submit button click

String toggle_text = toggleButton.getText().toString();

toggle_text String will give the present state of the toggle button.

output

android-toggle-button
android-toggle-button

 

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

Add a Comment

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