Android - The check box creation and event handler mechanism

 This is simple example for creating check box in android application. I have created the new android project and I have modified the main.xml file present in the layout folder with following code.


 Here I have just drag and drooped the check box control and I have changed the text value as "The Checkbox is unchecked". Now I am going to add the on change listener for this check box. I have changed the main java file and this is my code.

import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class BasicInputsActivity extends Activity implements OnCheckedChangeListener{
    /** Called when the activity is first created. */
       CheckBox checkBox1;
    public void onCreate(Bundle savedInstanceState) {
        checkBox1 = (CheckBox)findViewById(;

       public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
              if(checkBox1.isChecked()) {
                     checkBox1.setText("The Checkbox is checked");
              else {
                     checkBox1.setText("The Checkbox is unchecked");

 For adding on change listener for Check box I have implemented the OnCheckChangeListener interface as well as I have override the onCheckedChanged method. Finally I have checked whether the check box is created or not based on this condition I have changed the text value of check box using setText function. If you preview this application you can able to get the result like this.

 The setChecked() and toggle() are other important methods of CheckBox .


Popular Posts