Overview

Like a RadioButton, CheckBox is another type of two-state button that is either checked or unchecked. In fact, the CheckBox widget is quite similar to the Switch widget. If we compare with their functionality. By default, both come with the unchecked state or off state which means the checked state is false (android:checked=”false”).

CheckBox in Android

There are so many usages of CheckBoxes. For example, you can use a CheckBox in a MusicPlayer app to mute and unmute the audio or use it to enable the Dark theme in your app.


Create a CheckBox in Android Studio

There are two ways to create a CheckBox in Android Studio. First, you can simply drag & drop it from the palette section of the design panel. And secondly, you can use the XML editor.

Drag and drop in the design panel

Syntex:

 <CheckBox
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="Write text here..."/>

CheckBox initialization in Java

 <CheckBox
     android:id="@+id/checkbox_mute_audio"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="Mute Audio"/>

In order to initialize an XML version of CheckBox in java, we should create an instance of the CheckBox class. Then call the findViewById() method and pass the id of the CheckBox. As shown below code snippets. And this initialization should be done in the onCreate() method.

CheckBox checkBoxMuteAudio = findViewById(R.id.checkbox_mute_audio);

Useful Attributes and methods of CheckBox in Android

🔷 setChecked() or android:checked

By default, CheckBox comes with unchecked state. You can enable the checked state using android:checked attribute with true value. Unlike XML, you can check and uncheck a CheckBox from Java as well. As shown below.

Java

checkBoxMuteAudio.setChecked(true);

XML

android:checked=”true”

Even though you can pass false value if you want to uncheck it back. Simple!

🔷 isChecked()

Yes, you can call isChecked() method to get the current state of the CheckBox in Android. See below:

checkBoxMuteAudio.isChecked();

Basically, this method returns either true or false, depending upon the state of the CheckBox.

🔷 android:text or setText()

You can use the android:text attribute in the XML to set some text to your CheckBox. But in Java, you can call the setText() method to set some texts. As shown below.

Java

checkBoxMuteAudio.setText(“Option A”);

XML

android:text=”Option A”

Unlike setText() or android:text, you can also use padding, textColor, margin and many more attributes. So these have been explained in the TextView Section.


Interact with CheckBox in Android

Now you can set a listener with your CheckBox. If you want to interact with it. For that, you can use OnClickListener or OnCheckedChangeListener interface. How to do that?

Well, let’s have a look one by one!

CheckBox with OnCheckedChangeListener
checkBoxMuteAudio.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
     @Override
     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
          //...Write code...
     }
});

CheckBox with OnClickListener
checkBoxVisibility.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
         boolean isChecked = ((CheckBox)v).isChecked();
         updateTextVisibility(isChecked);
     }
});

Example of the CheckBox in Android

Now Let’s consider an example to understand how CheckBox works. Basically, we are going to use a CheckBox, a TextView and RelativeLayout as the parent layout. So we are going to build something like the below graphics, if the checkbox is checked then only the TextView will be visible otherwise not.



XML

activity_main.xml

<?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=".MainActivity">

    <TextView
        android:id="@+id/txtHelloWorld"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:layout_centerInParent="true"
        android:textSize="38sp"
        android:textStyle="bold"/>

    <CheckBox
        android:id="@+id/checkBox_visibility"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show text"
        android:checked="false"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="12dp"
        android:textSize="18sp"/>

</RelativeLayout>

Java

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private CheckBox checkBoxVisibility;
    private TextView txtHelloWorld;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //Initializing CheckBox and TextView
        checkBoxVisibility = findViewById(R.id.checkBox_visibility);
        txtHelloWorld = findViewById(R.id.txtHelloWorld);

        //Updaing UI by getting the Default state at the beginning...
        boolean isChecked = checkBoxVisibility.isChecked();
        updateTextVisibility(isChecked);

        // You can also use set the OnClickListener as well
        checkBoxVisibility.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                //Step 05 - Updating UI according to the currently changed state 
                updateTextVisibility(isChecked);
            }
        });
    }

    private void updateTextVisibility(boolean isChecked) {
        //Checking if isChecked is equal to true or false. 
        //And just hiding and unhiding the TextView (txtHelloWorld)
        if (isChecked) {
            txtHelloWorld.setVisibility(View.VISIBLE);
        } else {
            txtHelloWorld.setVisibility(View.INVISIBLE);
        }
    }
}

Build the project

So if we run these above code snippets then you see something like this below animation.

Android CheckBox Example

I hope you got all the points of Android AutoCompleteTextView. Anyway if you liked this article then please Subscribe to our Youtube channel for keeping this talk continue. You can also find us on Facebook and Instagram. Thanks for your support.

Translate »