Android CheckBox Example

The CheckBox object is a widely used UI component in android applications. android.widget.CheckBox is the java class that implements the checkbox in android. This article will show you an example of how to use this class and how to use the OnCheckedChangeListener to listen to the checkbox selection change event.

1. Example Screen Effect And Project File Structure.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/0vRysL6QU_o

  1. Below is the project files structure. The core files are activity_check_box.xml, strings.xml, CheckBoxActivity.java, AndroidManifest.xml.
    D:\WORK\DEV2QA.COM-EXAMPLE-CODE\ANDROIDEXAMPLEPROJECT\EXAMPLE
    │
    ├─app
    │  │  .gitignore
    │  │  build.gradle
    │  │  proguard-rules.pro
    │  │
    │  └─src
    │      │
    │      ├─main
    │      │  │  AndroidManifest.xml
    │      │  │
    │      │  ├─java
    │      │  │  └─com
    │      │  │      └─dev2qa
    │      │  │          └─example
    │      │  │              │  CheckBoxActivity.java
    │      │  │
    │      │  └─res
    │      │      │
    │      │      ├─layout
    │      │      │      activity_check_box.xml
    │      │      │
    │      │      ├─values
    │      │      │      strings.xml

2. activity_check_box.xml Layout File.

  1. This is the layout XML file saved in the app/res/layout folder, it contains three CheckBox UI components.
  2. You can set android:checked=”true” to make a checkbox checked by default.
  3. activity_check_box.xml
    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.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="com.dev2qa.example.CheckBoxActivity">
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            tools:layout_editor_absoluteX="8dp"
            tools:layout_editor_absoluteY="8dp">
    
            <TextView
                android:id="@+id/textView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/select_fruit_label" />
    
            <CheckBox
                android:id="@+id/checkBoxApple"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/fruit_apple"
                android:checked="true" />
    
            <CheckBox
                android:id="@+id/checkBoxBanana"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/fruit_banana" />
    
            <CheckBox
                android:id="@+id/checkBoxWatermelon"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/fruit_watermelon" />
    
            <Button
                android:id="@+id/checkBoxBtn"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/button_show_selection" />
        </LinearLayout>
    </android.support.constraint.ConstraintLayout>

3. Custom String strings.xml File.

  1. This file is saved in the app/res/values folder.
  2. strings.xml
    <resources>
        <string name="app_name">Example</string>
    
        <string name="select_fruit_label">Select Favorite Fruit : </string>
        <string name="fruit_apple">Apple</string>
        <string name="fruit_banana">Banana</string>
        <string name="fruit_watermelon">Watermelon</string>
    
        <string name="button_show_selection">Show Selection</string>
    
    </resources>

4. CheckBoxActivity.java

  1. This is the activity class. It contains two listeners to listen to CheckBox on checked change event ( OnCheckedChangeListener ) and button on click event ( OnClickListener ).
  2. CheckBoxActivity.java
    package com.dev2qa.example;
    
    import android.app.AlertDialog;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.CheckBox;
    import android.widget.CompoundButton;
    
    public class CheckBoxActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_check_box);
    
            // Register checkbox OnCheckedChangeListener object.
            CheckBox checkBoxApple = (CheckBox)findViewById(R.id.checkBoxApple);
            checkBoxApple.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
                    String showMsg = "";
                    if(checked)
                    {
                        // When checkbox is checked.
                        showMsg = "You check " + compoundButton.getText();
                    }else
                    {
                        // When checkbox is unchecked.
                        showMsg = "You uncheck " + compoundButton.getText();
                    }
    
                    // Create an AlertDialog object.
                    AlertDialog alertDialog = new AlertDialog.Builder(CheckBoxActivity.this).create();
    
                    // Set prompt message.
                    alertDialog.setMessage(showMsg);
    
                    // Show the alert dialog.
                    alertDialog.show();
    
                }
            });
    
            Button showSelectionBtn = (Button)findViewById(R.id.checkBoxBtn);
            showSelectionBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // Get three CheckBox object by id.
                    CheckBox checkBoxApple = (CheckBox) findViewById(R.id.checkBoxApple);
                    CheckBox checkBoxBanana = (CheckBox) findViewById(R.id.checkBoxBanana);
                    CheckBox checkBoxWatermelon = (CheckBox) findViewById(R.id.checkBoxWatermelon);
    
                    StringBuffer msgBuffer = new StringBuffer();
    
                    if(checkBoxApple.isChecked())
                    {
                        msgBuffer.append("Apple ");
                    }
    
                    if(checkBoxBanana.isChecked())
                    {
                        msgBuffer.append("Banana ");
                    }
    
                    if(checkBoxWatermelon.isChecked())
                    {
                        msgBuffer.append("Watermelon.");
                    }
    
                    if(msgBuffer.length()==0)
                    {
                        msgBuffer.append("Please select at least one favorite fruit.");
                    }else
                    {
                        msgBuffer.insert(0, " Your favorite fruits are ");
                    }
                    // Create an AlertDialog object.
                    AlertDialog alertDialog = new AlertDialog.Builder(CheckBoxActivity.this).create();
    
                    // Set prompt message.
                    alertDialog.setMessage(msgBuffer);
    
                    // Show the alert dialog.
                    alertDialog.show();
                }
            });
    
        }
    }

5. AndroidManifest.xml

  1. AndroidManifest.xml
    <activity android:name=".CheckBoxActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
    
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.