Sunday, August 26, 2012

Add Listener To Checkbox in Android


This next code sample is to show how to add a listener to a checkbox in Android.

It's pretty simple, first thing you will need to do is get the instance of the checkbox using findViewById or you can create the checkbox dynamically.  After tha, you add a OnCheckChanged listener, then test the boolean isChecked to see if it was checked or not.  That's it!

Some imports required...
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;


Here is the code....


CheckBox checkbox=(CheckBox) findViewById(R.id.checkBox);
checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
   {
       if ( isChecked )
       {    
           //add code to handle checkbox being checked
       }else
       {
           //add code to handle checkbox being unchecked
       }
    }
}