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.
Step 1: Create a new project with name switchexample and package name com.myexample.myswitch. Select File -> New -> New Project. Fill the forms and click “Finish” button.
Step 2: Open res -> layout -> xml (or) main.xml and add following code. Here we will create a Switch and a TextView in a RelativeLayout.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" tools:context=".MainActivity" android:background="#FFFFFF"> <Switch android:id="@+id/switchButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:onClick="onSwitchClick"/> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="100dp" android:layout_centerVertical="true" android:layout_centerHorizontal="true" android:layout_above="@+id/switchButton" android:textStyle="bold" android:textColor="#000000"/> </RelativeLayout>
Step 3: Open app -> java -> package and open MainActivity.java. Add following code in it. Here when the switch is clicked, we will display if the switch is on or off in a TextView.
package com.myexample.myswitch; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Switch; import android.widget.TextView; public class MainActivity extends Activity { Switch switchButton; TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); switchButton = (Switch) findViewById(R.id.switchButton); textView = (TextView) findViewById(R.id.textView); } public void onSwitchClick(View view){ if(switchButton.isChecked()){ textView.setText("Switch is ON"); } else{ textView.setText("Switch is OFF"); } } }
Output:
Now run the app. When you switch on the Switch, it will display ‘Switch is ON’, and when you switch it off it will display ‘Switch is OFF’.