Create event when checkBox is checked

by / Monday, 12 August 2013 / Published in Android

Checkboxes allow the user to select one or more options from a set. Typically,  each checkbox option should be presented in a vertical list.To create each checkbox option, create a CheckBox in your layout. Because a set of checkbox options allows the user to select multiple items, each checkbox is managed separately and  a click listener must be registered for each one.

Code for layout:

<CheckBox
android:id="@+id/chk_football"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/chk_football" />

<string name="chk_football">Football</string>//declare it in strings.xml

code for Activity:

private CheckBox chkFootball;

addListenerOnChkFootball();

public void addListenerOnChkFootball() {

chkFootball = (CheckBox) findViewById(R.id.chk_football);

chkFootball.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
//is chkIos checked?
if (((CheckBox) v).isChecked()) {
Toast.makeText(MainActivity.this,
"Football is checked :)", Toast.LENGTH_LONG).show();
}

}
});

}

 

 

 

Tagged under: ,
TOP