Android SwitchCompat Example Tutorial

Please follow and like us:

android switchcompat example tutorial
Android SwitchCompat Example- It’s now possible to backward compatibility to use Switch component in older devices and same user interface to all devices. Simple Android SwitchCompat Example is given in this tutorial. For backward compatibility of android switch you need add appcompat v7 library in your project

Android SwitchCompat Example Tutorial

 
First, add Appcompat support library in app’s build.gradle dependency

compile 'com.android.support:appcompat-v7:23.1.1'

Then add Android SwitchCompat in your layout file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".MainActivity">
 
    <android.support.v7.widget.SwitchCompat
        android:layout_centerInParent="true"
        android:id="@+id/switch_compat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="false"
        android:text="Android SwitchCompat Example"
        android:textOff="0"
        android:textOn="1"
        app:showText="true"/>
</RelativeLayout>

Now add main logic of Android SwitchCompat with listener in your java file

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SwitchCompat;
import android.widget.CompoundButton;
import android.widget.Toast;
 
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SwitchCompat switchCompat = (SwitchCompat) findViewById(R.id.switch_compat);
        switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Toast.makeText(MainActivity.this,"Android SwitchCompat Example Value "+isChecked,Toast.LENGTH_LONG).show();
            }
        });
    }
}

Hope you like our Android SwitchCompat Example…

nirav kalola