• Meghan Gill

Android SwitchMaterial (On/Off) Button Tutorial With Example

Updated: Jul 10, 2021


A switch widget is two state (On/Off) toggle button and a type of #selectioncontrol. Selection controls allow users to complete tasks which involve making choices such as selecting options, switching settings on or off, or adding or removing items.


Switches toggle a setting on or off. They are the preferred way to adjust settings on mobile.


Use switches to:

  • Toggle a single item on or off, on mobile and tablet

  • Immediately activate or deactivate something

Two States


A Switch represents a button with two states, on and off.


Switches are most often used on mobile devices to enable and disable options in an options menu.



Anatomy of a Switch


A switch consists of a track and thumb; the thumb moves along the track to indicate its current state.


Switches support #MaterialTheming and can be customized in terms of color and typography.

The SwitchMaterial widget provides a complete implementation of Material Design's switch component. It extends from the support library's SwitchCompat widget


Is Android SwitchMaterial backward compatible?

This class uses attributes from the Material Theme to style a Switch. Excepting color changes, it behaves identically to SwitchCompat. Therefore it is backwards compatible. As stated before, SwitchMaterial extends SwitchCompat so it is the newer version.


Attributes


SwitchMaterial has several attributes.


android:text


You can add text to the switch in XML or programmatically:



You can add various text attributes to the switch in XML:


android:textColor


android:textSize


android:textAppearance


android:textStyle






Further attributes include, padding and background color. The following example has both:



Add drawables to the top, bottom, left or right of the text of the SwitchMaterial. The example here adds a drawable below the text. Feel free to experiment with positioning yourself.





SwitchMaterial Example App


Step 1: Create a new Android Studio project with an Empty Activity. Name the project SwitchMaterialExample.


The Save location should be a place that makes sense on your computer. If you click on the open folder you can choose a location.


Choose Java or Kotlin. Pick a minimum SDK of API 21: Android 5.0 (Lollipop). You do not need any legacy android support libraries.




Add the Widgets


Create a SwitchMaterial button. Name it passwordSwitch.




Find your Switch in Code


Step 2: Create a SwitchMaterial variable and connect it to your UI widget. This example is in Java.



Set a Listener


Step 3: Set an onCheckedChangedListener(). As a parameter type new then control + space to enable the interface.


It is important to note, we can check the current state of a Switch programmatically by using isChecked() method.


This method returns a Boolean value (true or false). If a Switch is checked then it returns true, otherwise it returns false.



Step 4: Add a log statement to check if your switch is registering programmatically.




Run the app


You now have a working SwitchMaterial.

SwitchMaterial Off
SwitchMaterial On


Now what?


Learn more about UI by checking out more #selectioncontrols such as the #checkbox or #radioButton.


Also, learn how to save user preferences with #SharedPreferences APIs.


Source code for activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity"
    android:layout_margin="24dp">

    <TextView
        android:id="@+id/tVPrivacy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Privacy"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"/>

    <TextView
        android:id="@+id/tVshowPassword"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show passwords"
        app:layout_constraintTop_toBottomOf="@id/tVPrivacy"
        app:layout_constraintStart_toStartOf="parent"
        android:layout_marginTop="32dp"/>


    <TextView
        android:id="@+id/tVpasswordDescription"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Display characters briefly as you type"
        app:layout_constraintTop_toBottomOf="@id/tVshowPassword"
        app:layout_constraintStart_toStartOf="parent"/>

    <com.google.android.material.switchmaterial.SwitchMaterial
        android:id="@+id/passwordSwitch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBaseline_toBaselineOf="@id/tVshowPassword"/>


</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java:


package io.meghandev.switchmaterialexample;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.CompoundButton;
import com.google.android.material.switchmaterial.SwitchMaterial;

public class MainActivity extends AppCompatActivity {
    SwitchMaterial passwordSwitch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        passwordSwitch = findViewById(R.id.passwordSwitch);

        passwordSwitch.setOnCheckedChangeListener(
                new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(
                CompoundButton buttonView, boolean isChecked) {
                    Log.d("TAG", "Password Switch is checked " + 
                        isChecked);
            }
        });
    }
}

1,399 views0 comments

Recent Posts

See All