top of page
  • Writer's pictureMeghan Gill

Android MaterialCheckbox Example Tutorial


WhatsApp's storage and data settings for roaming
WhatsApp's storage and data settings for roaming

Checkboxes are 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.


Android CheckBox class is the subclass of the CompoundButton class. It is generally used in a place where users can select one or more choices from a given list of choices



Checkbox Usage


Checkboxes allow the user to select one or more items from a set. You should use a #checkbox when presenting a group of selectable options to users that are not mutually exclusive.


Checkboxes can be used to turn an option on or off. One very common use of CheckBox is as the remember me option in a Login form.



YouTube History settings in a Gmail account, showing a switch and checkboxes.
YouTube History settings in a Gmail account.
*Important note: In Android each checkbox is independent. On other platforms where Material design is used checkboxes can have a parent-child relationship. That does not apply to Android.


Checkbox Attributes


By default checkboxes appear at the left and are followed by their text.


android:text

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


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


android:textColor


android:textSize


android:textAppearance


android:textStyle


Further attributes include, padding, gravity and background color.


You can even place the checkbox on the right and have the text at the left using the drawableEnd attribute and setting the button attribute to null. See the "Morning Briefing" checkbox below:




Material Checkbox Example App


In this tutorial we use MaterialCheckboxes as a #selectioncontrol in the settings of a news app. A user can select checkboxes to choose which notifications to receive.


News Notifications options with checkboxes
Checkboxes for notification settings

Checkboxes are the best selection control option here, because the choices are nonexclusive - they can choose one option, two options or all three.


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


Step 2: Add the TextView and the 3 MaterialCheckBoxes using the code below:


<?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/tVNotifications"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="News Notifications"
        android:textAppearance="@style/TextAppearance.AppCompat.Headline"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
       />

    <com.google.android.material.checkbox.MaterialCheckBox
        android:id="@+id/checkBoxBreakingNews"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@id/tVNotifications"
        android:text="Breaking News"
        />

    <com.google.android.material.checkbox.MaterialCheckBox
        android:id="@+id/checkBoxMorningBriefing"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@id/checkBoxBreakingNews"
        android:text="Morning Briefing"/>

    <com.google.android.material.checkbox.MaterialCheckBox
        android:id="@+id/checkBoxEveningBriefing"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@id/checkBoxMorningBriefing"
        android:text="Evening Briefing"/>


</androidx.constraintlayout.widget.ConstraintLayout>

Find your Checkbox in Code


Step 3: Create a variable for each of the checkboxes in your MainActivity. Connect them to the UI widgets.



Set a Listener


Step 4: Set an onCheckedChangedListener() for each checkbox. 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 checkbox programmatically by using isChecked() method.


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




Include a Toast


Place a Toast inside each onCheckedChangedListener, so that the user receives a message each time they subscribe to a news notification. The toasts are shown in the screenshot above, but for a quick reference here's the news notifications toast:


    Toast.makeText(MainActivity.this,
        "You are now subscribed to breaking news notifications",
        Toast.LENGTH_SHORT).show();


Run the app



Now what?


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



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/tVNotifications"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="News Notifications"
        android:textAppearance="@style/TextAppearance.AppCompat.Headline"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
       />

    <com.google.android.material.checkbox.MaterialCheckBox
        android:id="@+id/checkBoxBreakingNews"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@id/tVNotifications"
        android:text="Breaking News"
        />

    <com.google.android.material.checkbox.MaterialCheckBox
        android:id="@+id/checkBoxMorningBriefing"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@id/checkBoxBreakingNews"
        android:text="Morning Briefing"/>

    <com.google.android.material.checkbox.MaterialCheckBox
        android:id="@+id/checkBoxEveningBriefing"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@id/checkBoxMorningBriefing"
        android:text="Evening Briefing"/>


</androidx.constraintlayout.widget.ConstraintLayout>


MainActivity.java:

package io.meghandev.checkboxesexample;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.Toast;

import com.google.android.material.checkbox.MaterialCheckBox;

public class MainActivity extends AppCompatActivity {
    MaterialCheckBox checkBoxBreakingNews;
    MaterialCheckBox checkBoxMorningBriefing;
    MaterialCheckBox checkBoxEveningBriefing;

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

        checkBoxBreakingNews = 
                findViewById(R.id.checkBoxBreakingNews);
        checkBoxMorningBriefing = 
                findViewById(R.id.checkBoxMorningBriefing);
        checkBoxEveningBriefing = 
                findViewById(R.id.checkBoxEveningBriefing);

        checkBoxBreakingNews.setOnCheckedChangeListener(new 
                CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView,     
                   boolean isChecked) {
                        Toast.makeText(MainActivity.this,
                        "You are now subscribed to breaking news 
                            notifications",
                        Toast.LENGTH_SHORT).show();
            }
        });

        checkBoxMorningBriefing.setOnCheckedChangeListener(new 
                CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, 
                    boolean isChecked) {
                        Toast.makeText(MainActivity.this,
                        "You are now subscribed to morning briefing         
                            notifications",
                        Toast.LENGTH_SHORT).show();
            }
        });

        checkBoxEveningBriefing.setOnCheckedChangeListener(new 
                CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, 
                    boolean isChecked) {
                        Toast.makeText(MainActivity.this,
                        "You are now subscribed to evening briefing 
                            notifications",
                        Toast.LENGTH_SHORT).show();
            }
        });
    }
}
2,067 views0 comments

Recent Posts

See All
bottom of page