Android UI How to - Create CheckBox








The CheckBox control is another two-state button that allows the user to toggle its state.

In Android, you can create a check box by creating an instance of android.widget.CheckBox.

Example

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
/*  w  w  w  .j a v a  2s.  c  o  m*/
    <CheckBox
        android:id="@+id/chickenCB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        android:text="XML" />

    <CheckBox
        android:id="@+id/fishCB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CSS" />

    <CheckBox
        android:id="@+id/steakCB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        android:text="HTML" />

</LinearLayout>

Java code

package com.java2s.app;
/* w ww. jav  a  2  s.c  o  m*/
import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }
}
null

You manage the state of a check box by calling setChecked() or toggle(). You can obtain the state by calling isChecked().