Listening to checkBox stateChange in Android

By | February 14, 2012

This is a simple example showing how to listen to checkbox in android. To check whether the checkbox is in on state or in off state just add a listener to the checkbox you want to listen.

This is how we do this.

ch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
});

This is the layout contaning a checkbox.

<?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"
    >
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Coderzheaven CheckBox Demo"
        />
    <CheckBox
        android:text="Check Me"
        android:id="@+id/CheckBox01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </CheckBox>
</LinearLayout>

This is the java code for listening to the state change

package com.coderzheaven.pack;
 
import android.app.Activity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
 
public class CheckBoxDemo extends Activity {
    CheckBox ch;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        ch = (CheckBox)findViewById(R.id.CheckBox01);
        ch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
 
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    Toast.makeText(getApplicationContext(), "Checked", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(getApplicationContext(), "Not Checked", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

Download the sample code here

Please leave in your valuable comments on this post.

One thought on “Listening to checkBox stateChange in Android

Leave a Reply

Your email address will not be published. Required fields are marked *