Check Box

A checkbox for selecting items. We'll make it display the the current state when pressed. 1. Open the layout file and, inside the LinearLayout, add the CheckBox element:

<CheckBox android:id="@+id/checkbox"

android:layout width="wrap content" android:layout height="wrap content" android:text="check it out" />

2. To do something when the state is changed, add the following code to the end of the onCreate() method:

final CheckBox checkbox = (CheckBox) findViewById(;

checkbox.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

// Perform action on clicks if (checkbox.isChecked()) {

Toast.makeText(HelloFormStuff.this, "Selected", Toast.LENGTH_SHORT).show();

Toast.makeText(HelloFormStuff.this, "Not selected",

This captures our CheckBox element from the layout, then adds an on-click listener to it. The View.OnClickListener must define the onClick() method, which defines the action to be made when the checkbox is clicked. Here, we query the current state of the checkbox, then pop up a Toast message that displays the current state. Notice that the CheckBox handles its own state change between checked and un-checked, so we just ask which it currently is. 3. Run it.

Tip: If you find that you need to change the state in another way (such as when loading a saved CheckBoxPreference), use setChecked(true) or toggle() .

0 0

Post a comment