Main Tutorials

Android checkbox example

In Android, you can use “android.widget.CheckBox” class to render a checkbox.

In this tutorial, we show you how to create 3 checkboxes in XML file, and demonstrates the use of listener to check the checkbox state – checked or unchecked.

P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.

1. Custom String

Open “res/values/strings.xml” file, add some user-defined string.

File : res/values/strings.xml


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, MyAndroidAppActivity!</string>
    <string name="app_name">MyAndroidApp</string>
    <string name="chk_ios">IPhone</string>
    <string name="chk_android">Android</string>
    <string name="chk_windows">Windows Mobile</string>
    <string name="btn_display">Display</string>
</resources>

2. CheckBox

Open “res/layout/main.xml” file, add 3 “CheckBox” and a button, inside the LinearLayout.

File : res/layout/main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <CheckBox
        android:id="@+id/chkIos"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/chk_ios" />
		
    <CheckBox
        android:id="@+id/chkAndroid"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/chk_android"
        android:checked="true" />

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

    <Button
        android:id="@+id/btnDisplay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btn_display" />

</LinearLayout>
Make CheckBox is checked by default
Put android:checked="true" inside checkbox element to make it checked bu default. In this case, “Android” option is checked by default.

3. Code Code

Attach listeners inside your activity “onCreate()” method, to monitor following events :

  1. If checkbox id : “chkIos” is checked, display a floating box with message “Bro, try Android”.
  2. If button is is clicked, display a floating box and display the checkbox states.

File : MyAndroidAppActivity.java


package com.mkyong.android;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;

public class MyAndroidAppActivity extends Activity {

  private CheckBox chkIos, chkAndroid, chkWindows;
  private Button btnDisplay;

  @Override
  public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.main);

	addListenerOnChkIos();
	addListenerOnButton();
  }

  public void addListenerOnChkIos() {

	chkIos = (CheckBox) findViewById(R.id.chkIos);

	chkIos.setOnClickListener(new OnClickListener() {

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

	  }
	});

  }

  public void addListenerOnButton() {

	chkIos = (CheckBox) findViewById(R.id.chkIos);
	chkAndroid = (CheckBox) findViewById(R.id.chkAndroid);
	chkWindows = (CheckBox) findViewById(R.id.chkWindows);
	btnDisplay = (Button) findViewById(R.id.btnDisplay);

	btnDisplay.setOnClickListener(new OnClickListener() {

          //Run when button is clicked
	  @Override
	  public void onClick(View v) {

		StringBuffer result = new StringBuffer();
		result.append("IPhone check : ").append(chkIos.isChecked());
		result.append("\nAndroid check : ").append(chkAndroid.isChecked());
		result.append("\nWindows Mobile check :").append(chkWindows.isChecked());

		Toast.makeText(MyAndroidAppActivity.this, result.toString(),
				Toast.LENGTH_LONG).show();

	  }
	});

  }
}

4. Demo

Run the application.

1. Result :

android checkbox demo 1

2. If “IPhone” is checked :

android checkbox demo2

3. Checked “IPhone” and “Windows Mobile”, later, click on the “display” button :

android checkbox demo3

Download Source Code

Download it – Android-Checkbox-Example.zip (15 KB)

References

  1. Android CheckBox JavaDoc
  2. Android CheckBox example

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
23 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
John Champin
6 years ago

I had run this code. by the way I cannot find symbol variables: chkDriver, chkCarOwner, buttonDisplay. Please I wish to have your advice.

nanda kumar
7 years ago

how to arrange password edittext and checkbox(hide/show)?

Thomas
7 years ago

But how to check the widget programmaticaly? How to set text to appear on the left of the checkbox?

azeem
9 years ago

good

lavlesh
9 years ago

sir how can i arrange check box in single row

Smc
4 years ago
Reply to  lavlesh

By using linear layout orientation horizontal..

ashish
10 years ago

hi,is this possible without using xml (i.e. using java),because my reqirement is creating checkboxes dynamically

hariy
10 years ago

this is what I looking for. thanks from Indonesia 🙂

full
10 years ago

Thank you man, it helped me 🙂

full
10 years ago

Thank you man it helped me

robert
10 years ago

i have problem with this one

chkIos = (CheckBox) findViewById(R.id.chkIos);

and of course

chkIos = (CheckBox) findViewById(R.id.chkIos);
chkAndroid = (CheckBox) findViewById(R.id.chkAndroid);
chkWindows = (CheckBox) findViewById(R.id.chkWindows);
btnDisplay = (Button) findViewById(R.id.btnDisplay);

error about “chkIos cannot be resolved or is not a field”

Anik
9 years ago
Reply to  robert

you did not mention the type of chklos. you have to write like CheckBox chklos=(CheckBox) findViewById(R.id.chkIos);

Kaamz
10 years ago

As a beginner I like this site. Easy to understand each topic in detail..

Learned lot from here…. Hats off to U…

Abdul Latheef.A
11 years ago

Dear friend
Very Good tutorial and simple to understand.
Thank u
Latheef

Believer
11 years ago

Hi, I’m a software developer just like you. I just want to congratulate you for this fantastic work of delivering concrete and useful source code. I’m know that there is more of you that can be appreciated in your web pages. I don’t know if you are Christian and/or believe in The Lord Jesus Christ, but I will certainly include you in my prayers, as a Christian Catholic. God be with you, Lord Jesus Christ always protect you, and give you the strength to contribute more to the SW Developer Community with this kind of work. Thank you, and God bless you.

Minyong
10 years ago
Reply to  Believer

Oi kirig wag dito!

Reece
10 years ago
Reply to  Believer

Just stop. You’re devaluing the word “developer” by preaching your beliefs. This page/post isn’t about religion so don’t bother mentioning it, you just look like a fool.

JavaPeaceLoveAndHappiness
10 years ago
Reply to  Reece

He doesn’t look like a fool. Let the guy thank Minyong any way he likes. I am not Catholic but am not offended in anyway. You’re just tearing people down instead of being tolerant of different ideas.

devendra
11 years ago

Very good site for freshers many thanks for MKYONG.

Rick
11 years ago

How can I check dynamic checkbox ?

CheckBox cb = new CheckBox(this);
		cb.setId(Integer.valueOf(id));
		
		cb.setPadding(12, 0, 15, 0);
		cb.setTextColor(Color.WHITE);
		tr.addView(cb);
Frank
11 years ago

Thanks for your examples for android! 😉

Frank (Germany)

goso
9 years ago

what is the syntax of radiobutton

onks_
11 years ago

This was a tad helpful…thanks mkyong 🙂