The classic check box has two states: checked and
unchecked. Clicking the check box toggles between those states to
indicate a choice (e.g., "Add rush delivery to my order").
In Android, there is a CheckBox widget to meet this need. It has TextView as an ancestor, so you can use TextView properties like android:textColor to format the widget.
Within Java, you can invoke the following:
isChecked(): Determines if the check box has been checked
setChecked(): Forces the check box into a checked or unchecked state
toggle(): Toggles the check box as if the user checked it
Also, you can register a listener object (in this case, an instance of OnCheckedChangeListener) to be notified when the state of the check box changes.
For example, from the Basic/CheckBox project, here is a simple check box layout:
<?xml version="1.0" encoding="utf-8"?>
<CheckBox xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This checkbox is: unchecked" />
The corresponding CheckBoxDemo.java retrieves and configures the behavior of the check box:
public class CheckBoxDemo extends Activity
implements CompoundButton.OnCheckedChangeListener {
CheckBox cb;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
cb=(CheckBox)findViewById(R.id.check);
cb.setOnCheckedChangeListener(this);
}
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
cb.setText("This checkbox is: checked");
}
else {
cb.setText("This checkbox is: unchecked");
}
}
}
Note that the activity serves as its own listener for check box state changes, since it implements the OnCheckedChangeListener interface (via cb.setOnCheckedChangeListener(this)). The callback for the listener is onCheckedChanged(),
which receives the check box whose state has changed and the new state.
In this case, we update the text of the check box to reflect what the
actual box contains.
The result? Clicking the check box immediately updates its text, as shown in Figures 1 and 2.