How to Respond to Check Box Events in Your Android App

By Barry Burd

Why click twice when you can do the same thing by clicking only once? Your Android app may respond to the contents of check boxes when the user clicks a button. In a streamlined scenario, your app might respond as soon as the user checks a box. This code shows you how to make this happen.

package com.allyourcode.p01_06_04;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.
OnCheckedChangeListener;
import android.widget.TextView;
public class MainActivity extends Activity
implements OnCheckedChangeListener {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((CheckBox) findViewById(R.id.checkBox))
.setOnCheckedChangeListener(this);
((CheckBox) findViewById(R.id.checkBox2))
.setOnCheckedChangeListener(this);
textView =
(TextView) findViewById(R.id.textView);
}
@Override
public void onCheckedChanged(CompoundButton box,
boolean isChecked) {
StringBuilder str =
new StringBuilder(textView.getText());
CharSequence boxText = box.getText();
if (isChecked) {
str.append(“ “ + boxText);
} else {
int start = str.indexOf(boxText.toString());
int length = boxText.length();
str.replace(start, start + length, ““);
}
textView.setText(str.toString().trim());
}
//… Et cetera

Like a button, each check box listens for onClick events. You can avoid using the onClick property and illustrate the use of a different event listener.

A check box listens for changes to its state (its “checked” versus “unchecked” state). So when the user touches a check box, Android fires an onCheckedChanged event. By registering this (the entire MainActivity instance) as each check box’s OnCheckedChangeListener, you make Android call the onCheckedChanged method.

The onCheckedChanged method has two parameters — the component that was touched and the state of the component as a result of the touch. The code above was contrived to make use of these two method parameters.

A CompoundButton is a widget with checked and unchecked states. The CheckBox class is a subclass of CompoundButton. Other subclasses of CompoundButton are RadioButton and ToggleButton. A ToggleButton is that cute little thing that lights when it’s checked.

In the code you see above, the onCheckedChanged method’s box parameter refers to whichever check box the user touches. That check box has a getText method, so you use the getText method to help fill the textView element. You can use the onCheckedChanged method’s isChecked parameter to decide whether to add text to the textView element or delete text from the textView element.