Android CheckBox Introduction

April 11, 2018 Oclemy Android CheckBox 4 minutes, 26 seconds

A checkbox is a specific type of two-states button that can be either checked or unchecked.

Their primary role is to allow a user to select one or more option from a group of alternatives.

CheckBoxes are a popular way of representing Boolean values in Forms. Not only do they get used in mobile applications but also in desktop as well as online forms.

Android CheckBox

CheckBoxes, unlike RadioButtons, are managed independently of each other. Therefore each must handle its own events. This is because CheckBoxes, unlike RadioButtons, can be used to select many options, not just one.

A CheckBox is a CompoundButton in that it has two states. Also it does derive from the android.widget.CompoundButton class.

The CompoundButton is an abstract class defined in the android.widget package that acts as the interface definition for a callback to be invoked when the checked state of its child is changed.

The CompoundButton itself is a Button so CheckBox itself will inherit capabilities for Butttons.

CheckBox API Definition

The CheckBox resides in the android.widget namespace.

package android.widget;

It derives from android.widget.CompoundButton:

public class CheckBox extends android.widget.CompoundButton{}

Important Methods inherited From CompoundButton

Here are some of the important properties of CheckBox

Property Return Type Description
boolean isChecked () Boolean Determine if the checkBox is checked or not.Defined in the CompoundButton class.
void toggle () void Change the checked state of the view to the inverse of its current state. Also defined in the CompoundButton class.
void setChecked (boolean checked) void Changes the checked state of this button..Also defined in the CompoundButton class.
void setOnCheckedChangeListener (CompoundButton.OnCheckedChangeListener listener) void Register a callback to be invoked when the checked state of this button changes..Also defined in the CompoundButton class.

Definition in XML Layout

CheckBoxes can be defined in the XML layouts like most widgets.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <CheckBox android:id="@+id/checkbox_meat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/meat"
        android:onClick="onCheckboxClicked"/>
    <CheckBox android:id="@+id/checkbox_cheese"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/cheese"
        android:onClick="onCheckboxClicked"/>
</LinearLayout>

Manipulation From Java code.

Then CheckBox can be manipulated from the Java code.

public void onCheckboxClicked(View view) {
    // Is the view now checked?
    boolean checked = ((CheckBox) view).isChecked();

    // Check which checkbox was clicked
    switch(view.getId()) {
        case R.id.checkbox_meat:
            if (checked)
                // blah blah
            else
                // blah blah
            break;
        case R.id.checkbox_cheese:
            if (checked)
                // blah blah
            else
                // blah blah
            break;
    }
}

Normally when a CheckBox is selected, the onClick event is raised. So in the above example, we defined an android:onClick attribute of our XML layout then registered it an event handler.

Full Example

Let's now look at a full example in Java code. Here's the XML layout. We add a checkbox here.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="info.camposha.mrcheckbox.MainActivity">

    <TextView
        android:id="@+id/headerLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="casual"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="Mr. CheckBox"
        android:textAllCaps="true"
        android:textSize="24sp"
        android:textStyle="bold" />
    <CheckBox
        android:id="@+id/myCheckbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="CheckBox Unchecked"
        android:padding="5dp" />

</RelativeLayout>

Then here's our java code.

package info.camposha.mrcheckbox;

import android.app.Activity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;

public class MainActivity extends Activity {
    /*
    * When activity is Created.
    */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //reference checkbox
        final CheckBox myCheckBox = findViewById(R.id.myCheckbox);
        //register event handler
        myCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                myCheckBox.setText( compoundButton.isChecked() ? "CheckBox Checked" : "CheckBox Unchecked");
            }
        });
    }
}
  1. First we specify the package name to host our class.

  2. Then add our imports using the import directive.

  3. Then create a public class we call MainActivity that derives from android.app.Activity.

  4. We will then override the on onCreate() method which is a life cycle callback for android. It gets called when the activity is created.

  5. Fist we invoke the onCreate() method of the super class. That super class is the Activity. We pass it a bundle object.

  6. We invoke the setContentView() which is a method inside the activity class and will inflate our R.layout.activity_main.xml layout and use it as the view for our main activity.

  7. First we reference the CheckBox using the findViewById method, passing in the id from the layout.

    final CheckBox myCheckBox = findViewById(R.id.myCheckbox);
  8. We then attach our onCheckedChangeListener to our CheckBox. We override the onCheckedChange() callback.
    myCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            }
        });
  9. Inside it we set text depending on whether the checkbox is selected or not.
    myCheckBox.setText( compoundButton.isChecked() ? "CheckBox Checked" : "CheckBox Unchecked");

alt

Comments