Android Switch (ON / OFF) Button with Examples

  Total Views : 35
  Comments : 0
  Keywords : Android switch button control is a user interface element which is used to display checked / unchecked states as a button, Android switch button to toggle between either on or off states

Here we will learn switch button in android with examples and how to use android switch to toggle between two states either ON / OFF, use android switch with case statement and android switch listener with examples.

Android Switch UI Control

In android, Switch is a two-state user interface element which is used to display ON (Checked) or OFF (Unchecked) states as a button with thumb slider. By using thumb, the user may drag back and forth to choose an option either ON or OFF.

 

The Switch element is useful for the users to change the settings between two states either ON or OFF. We can add a Switch to our application layout by using Switch object.

 

Following is the pictorial representation of using Switch in android applications.

 

Android Switches Example Diagram

 

By default, the android Switch will be in OFF (Unchecked) state. We can change the default state of Switch by using android:checked attribute.

 

In case, if we want to change the state of Switch to ON (Checked), then we need to set android:checked = “true” in our XML layout file.

 

In android, we can create Switch control in two ways either in XML layout file or create it in Activity file programmatically.

Create Switch in XML Layout File

Following is the sample way to define Switch control in XML layout file in android application.

 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
android:layout_width="match_parent" android:layout_height="match_parent">
<
Switch
   
android:id="@+id/switch1"
   
android:layout_width="wrap_content"
   
android:layout_height="wrap_content"
   
android:switchMinWidth="56dp"
   
android:layout_marginLeft="100dp"
   
android:layout_marginTop="120dp"
   
android:text="Switch1:"
   
android:checked="true"
   
android:textOff="OFF"
   
android:textOn="ON"/>
</
RelativeLayout>

If you observe above code snippet, here we defined Switch control and setting Switch state ON using android:checked attribute and textOff / textOn attributes are used to set the text to represent Switch state in xml layout file.

Create Switch Control in Activity File

In android, we can create Switch control programmatically in activity file based on our requirements. 

 

Following is the example of creating Switch control dynamically in activity file.

 

RelativeLayout layout = (RelativeLayout)findViewById(R.id.r_layout);
Switch sb =
new Switch(this);
sb.setTextOff(
"OFF");
sb.setTextOn(
"ON");
sb.setChecked(
true);
layout.addView(sb);

This is how we can define Switch in XML layout file or programmatically in activity file based on our requirements.

Handle Switch Click Events

Generally, whenever the user clicks on Switch, we can detect whether the Switch is in ON or OFF state and we can handle Switch click event in activity file using setOnCheckedChangeListener like as shown below.

 

Switch sw = (Switch) findViewById(R.id.switch1);
sw.setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener() {
   
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
       
if (isChecked) {
           
// The toggle is enabled
       
} else {
           
// The toggle is disabled
       
}
    }
});

This is how we can handle Switch click events in android applications based on our requirements.

Android Switch Control Attributes

Following are the some of commonly used attributes related to Switch control in android applications.

 

AttributeDescription
android:id It is used to uniquely identify the control
android:checked It is used to specify the current state of switch control
android:gravity It is used to specify how to align the text like left, right, center, top, etc.
android:text It is used to set the text.
android:textOn It is used to set the text when toggle button is in ON / Checked state.
android:textOff It is used to set the text when toggle button is in OFF / Unchecked state.
android:textColor It is used to change the color of text.
android:textSize It is used to specify the size of text.
android:textStyle It is used to change the style (bold, italic, bolditalic) of text.
android:background It is used to set the background color for toggle button control.
android:padding It is used to set the padding from left, right, top and bottom.
android:drawableBottom It’s a drawable to be drawn to the below of text.
android:drawableRight It’s a drawable to be drawn to the right of text.
android:drawableLeft It’s a drawable to be drawn to the left of text.

Android Switch Control Example

Following is the example of defining a two Switch controls and one Button control in RelativeLayout to get the state of Switch controls when we click on Button control in android application.

 

Create a new android application using android studio and give names as SwitchExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.

 

Now open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
android:layout_width="match_parent" android:layout_height="match_parent">
    <
Switch
       
android:id="@+id/switch1"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:switchMinWidth="56dp"
       
android:layout_marginLeft="100dp"
       
android:layout_marginTop="120dp"
       
android:text="Switch1:"
       
android:checked="true"
       
android:textOff="OFF"
       
android:textOn="ON"/>
    <
Switch
       
android:id="@+id/switch2"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:switchMinWidth="56dp"
       
android:layout_below="@+id/switch1"
       
android:layout_alignLeft="@+id/switch1"
       
android:text="Switch2:"
       
android:textOff="OFF"
       
android:textOn ="ON"/>
    <
Button
       
android:id="@+id/getBtn"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_marginLeft="150dp"
       
android:layout_marginTop="200dp"
       
android:text="Get" />
</
RelativeLayout>

If you observe above code we defined a two Switch controls and one Button control in RelativeLayout to get the state of Switch controls when we click on Button control in XML layout file.

 

Once we are done with creation of layout with required controls, we need to load the XML layout resource from our activity onCreate() callback method, for that open main activity file MainActivity.java from \java\com.tutlane.switchexample path and write the code like as shown below.

MainActivity.java

package com.tutlane.switchexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
private Switch sw1,sw2;
   
private  Button btnGet;
   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);
       
sw1 = (Switch)findViewById(R.id.switch1);
       
sw2 = (Switch)findViewById(R.id.switch2);
       
btnGet = (Button)findViewById(R.id.getBtn);
       
btnGet.setOnClickListener(new View.OnClickListener() {
           
@Override
           
public void onClick(View v) {
                String str1, str2;
               
if (sw1.isChecked())
                    str1 =
sw1.getTextOn().toString();
               
else
                   
str1 = sw1.getTextOff().toString();
               
if (sw2.isChecked())
                    str2 =
sw2.getTextOn().toString();
               
else
                   
str2 = sw2.getTextOff().toString();
                Toast.makeText(getApplicationContext(),
"Switch1 -  " + str1 + " \n" + "Switch2 - " + str2,Toast.LENGTH_SHORT).show();
            }
        });
    }
}

If you observe above code we are calling our layout using setContentView method in the form of R.layout.layout_file_name in our activity file. Here our xml file name is activity_main.xml so we used file name activity_main and we are trying to get the state of two Switch controls on Button click.

 

Generally, during the launch of our activity, onCreate() callback method will be called by android framework to get the required layout for an activity.

Output of Android Switch Example

When we run above example using android virtual device (AVD) we will get a result like as shown below.

 

Android Switch Control Example Result

 

This is how we can use Switch control in android applications to switch the settings between two states either ON or OFF based on our requirements.

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User