
Toggle Buttons allows users to change state between two states like as On or Off.
Toggle Buttons can be easily added in your layout xml file using ToggleButton object.
you can ToggleButton like below way in your layout file:
<ToggleButton android:layout_width="wrap_content" android:layout_height="wrap_content"/>

You want to set actions on it then you can do this via java file, but first of all assign a id to it so that we can call it in our java or MainActivity.java file like as: android:id=”@+id/myToggleButton”
<ToggleButton android:id="@+id/myToggleButton" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
Now in your MainActivity.java file initialize the Toogle button via this id and then set the actions on it as shown in the below code inside the onCreate Method:
ToggleButton toggleButton = (ToggleButton)findViewById(R.id.myToggleButton); // initialize the toggle button using id toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { if (b) { // The toggle is enabled here showToast("Toggle button is enabled"); // showing toast using custom toast method } else { // The toggle is disabled here showToast("Toggle button is disabled"); // showing toast using custom toast method } } });
After click on Toggle button it will become on as showing in the screenshot:

If you want to set background and text color on your toggle button than you can add in your layout xml file via this way:
android:background="@color/colorPrimary" android:textColor="@color/white"
Gradient Toogle Button:
Yes you can also set Gradient color to your Android Toggle button using a drawable file, to set gradient you have to create a gradient drawable file and than set it as background of Toggle Button as like you set background color or text color:
<ToggleButton android:id="@+id/myToggleButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/gradeint" android:textColor="@color/white"/>


This is the gradeint Android Toogle button with both states off and on as shown in the images.
Leave a Comment
You must be logged in to post a comment.