Studyon Minte9.com
Android




Check Boxes



1) Click Events

Because a set of checkbox options allows the user to select multiple items, each checkbox is managed 
separately and you must register a click listener for each one.

This will display two checkboxes (male, female)

	%--- activity_main.xml

	<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	    android:orientation="vertical"
	    android:layout_width="fill_parent"
	    android:layout_height="fill_parent">
		
	    <CheckBox android:id="@+id/checkbox_male"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="@string/male"
		android:onClick="onCheckboxClicked"
		/>
	    
	    <CheckBox android:id="@+id/checkbox_female"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="@string/female"
		android:onClick="onCheckboxClicked"
		/>
	    
	</LinearLayout>


	%--- MainActivity.java

	package com.example.myapp;
	import android.app.Activity;
	import android.os.Bundle;
	import android.view.View;
	import android.widget.CheckBox;

	public class MainActivity extends Activity {
		     
	    @Override
	    protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	    }
	    
	    public void onCheckboxClicked(View view) {
		
		boolean checked = ((CheckBox) view).isChecked();
		
		switch(view.getId()) {
			case R.id.checkbox_male:
				break;
			case R.id.checkbox_female:
				break;
		}
	    }
	}


2) Toggle

If you need to change the radio button state yourself (such as when loading a saved 
CheckBoxPreference), use the setChecked(boolean) or toggle() method.
	
Both checkboxes will be checked from start.

	%--- MainActivity.java

	package com.example.myapp;
	import android.app.Activity;
	import android.os.Bundle;
	import android.view.View;
	import android.widget.CheckBox;

	public class MainActivity extends Activity {
		     
	    @Override
	    protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		CheckBox ck_1 = (CheckBox) findViewById(R.id.checkbox_male);
		ck_1.setChecked(true);
		
		CheckBox ck_2 = (CheckBox) findViewById(R.id.checkbox_female);
		ck_2.toggle();
	    }
	    
	    public void onCheckboxClicked(View view) {}
	}


http://developer.android.com/guide/topics/ui/controls/checkbox.html