Android switch tutorial

Switch (On/Off) Tutorial With Example In Android Studio

Switch: Switch is a two-state toggle switch widget that can select between two options. It is used to display checked and unchecked state of a button providing slider control to user. Switch is a subclass of CompoundButton. It is basically an off/on button which indicate the current state of Switch. It is commonly used in selecting on/off in Sound, Bluetooth, WiFi etc.

Step 1: Open up Android Studio Project through res -> layout -> activity_main.xml (or) main.xml and add below code or just drag and drop the switch to design XML file.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">


    <Switch
        android:id="@+id/simpleSwitch1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:checked="false"
        android:text="switch 1"
        android:textOff="Off"
        android:textOn="On" />

    <TextView 
        android:id="@+id/Textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
         />
       
</LinearLayout>

Step 3:Add below code in MainActivity.java to handle events on switch.

package com.bytelogs.example;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Switch;
import android.widget.Toast;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    Switch simpleSwitch1;
    TextView TextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // initiate view's
        simpleSwitch1 = (Switch) findViewById(R.id.simpleSwitch1);
        TextView = (TextView)findViewById(R.id.textView);
        if(simpleSwitch1.isChecked()){
            TextView.setText("Checked")
        }else{
            textView.setText("Unchecked")
        }

    }  
}