VOOZH about

URL: https://www.geeksforgeeks.org/android/how-to-use-checkbox-in-android/

⇱ How to use CheckBox in Android - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to use CheckBox in Android

Last Updated : 29 Jan, 2025

CheckBox belongs to android.widget.CheckBox class. Android CheckBox class is the subclass of CompoundButton class. It is generally used in a place where user can select one or more than choices from a given list of choices.

Syntax of CheckBox

public class CheckBox extends CompoundButton

It has two states - checked or unchecked.

Class Hierarchy :

java.lang.Object
↳ android.view.View
↳ android.widget.TextView
↳ android.widget.Button
↳ android.widget.CompoundButton
↳ android.widget.CheckBox

Methods of CheckBox class

  • public boolean isChecked(): If CheckBox is in checked state then return true otherwise false.
  • public void setChecked(boolean status): It changes the state of the CheckBox.

Example of CheckBox in Android

Below is the code for an example where the user chooses its hobbies from the given list containing Painting, Reading, Singing and Cooking with the help of CheckBox.

1. Working of Layout

The activity_main.xml has a TextView, 4 CheckBoxes and a button.The TextView prompts the user to select his/her hobbies. First user select its choices and then presses the Submit button. After pressing Submit button, a toast will generate showing the selected hobbies.

activity_main.xml:

Layout:

👁 CheckBox_Layout

Note: The Application is using android:onClick="Check" in xml file which help us to call the Check method when the button is clicked.

2. Modification of the MainAcitivity File

Now, after creating the layout we want to add the functionality to the application/layout.

MainActivity File:

Output: ( Selecting and Pop-Up/Toast the Selection)


Comment

Explore