Android CheckBox Example

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

1. Example Screen Effect And Project File Structure.

android checkbox example

Below is the project files structure. The core files are : activity_check_box.xml, strings.xml, CheckBoxActivity.java, AndroidManifest.xml.

android checkbox example project files structure

2. activity_check_box.xml Layout File.

This is the layout xml file saved in app / res / layout folder, it contains three CheckBox UI components. You can set android:checked="true" to make a checkbox checked by default.

<?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.

This file is saved in app / res / values folder.

<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

This is the activity class. It contains two listeners to listen CheckBox on checked change event ( OnCheckedChangeListener ) and button on click event ( OnClickListener ).

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

<activity android:name=".CheckBoxActivity">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
(Visited 1,014 times, 1 visits today)
READ :   Android Tab, Shadow Button Example

Leave a Reply

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.