How to Check if CheckBox is Checked in Android?
Checkbox is a UI element mostly found in websites and applications around us. They are square-shaped boxes ahead of a choice or a statement. When a user clicks on it, they get ticked. They are most commonly found in electronic forms in websites and applications where the user needs to make one or many choices. Most of us must have checked them while agreeing to policies of one or more applications. We see that unless they are checked, we cannot proceed ahead.
So in this article, we will show you how you can implement a CheckBox in an Android application and add functionality to it such that one can proceed only if the Checkbox is checked. Follow the below steps once the IDE is ready.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Place a TextView, a CheckBox, and a Button in the activity layout file.
Step 3: Working with the MainActivity.kt file
Basically, we add functionality to the Button, that if the CheckBox is checked, a Toast message would appear. Here we can add an intent to move to the next activity. If the CheckBox is not checked, then the Checkbox text changes to “Please Accept this!” and turns the text color to red. Refer to the comments.
You can see that if we click the Button without checking the CheckBox, the CheckBox text changes. Now, if we check the CheckBox and click the Button, we get a Toast message.