Skip to main content

How to use CheckBox in Android

1. Android CheckBox Example

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    >
    <CheckBox
        android:id="@+id/checkbox_red"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Red"
        android:onClick="onCheckBoxClicked"
        />
    <CheckBox
        android:id="@+id/checkbox_brown"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Brown"
        android:onClick="onCheckBoxClicked"
        android:layout_below="@id/checkbox_red"
        />
    <CheckBox
        android:id="@+id/checkbox_yellow"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Yellow"
        android:onClick="onCheckBoxClicked"
        android:layout_below="@id/checkbox_brown"
        />
    <CheckBox
        android:id="@+id/checkbox_crimson"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Crimson"
        android:onClick="onCheckBoxClicked"
        android:layout_below="@id/checkbox_yellow"
        />
    <CheckBox
        android:id="@+id/checkbox_indigo"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Indigo"
        android:onClick="onCheckBoxClicked"
        android:layout_below="@id/checkbox_crimson"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidexamples;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

//additional imported classes
import android.view.View;
import android.widget.CheckBox;
import android.graphics.Typeface;


public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    public void onCheckBoxClicked(View v){
        //Get reference of the CheckBoxes
        CheckBox cb_red = (CheckBox) findViewById(R.id.checkbox_red);
        CheckBox cb_brown = (CheckBox) findViewById(R.id.checkbox_brown);
        CheckBox cb_yellow = (CheckBox) findViewById(R.id.checkbox_yellow);
        CheckBox cb_crimson = (CheckBox) findViewById(R.id.checkbox_crimson);
        CheckBox cb_indigo = (CheckBox) findViewById(R.id.checkbox_indigo);

        //Is the view (Clicked CheckBox) now checked
        boolean checked = ((CheckBox) v).isChecked();

        //So, check which CheckBox was Clicked and generated a Click event
        switch(v.getId()){ //get the id of clicked CheckBox
            case R.id.checkbox_red:
                if (checked){
                    //if 'Red' CheckBox checked, changed its text to bold and italic
                    cb_red.setTypeface(cb_red.getTypeface(), Typeface.BOLD_ITALIC);
                }
                else{
                    //if 'Red' CheckBox unchecked, changed its text to normal state
                    cb_red.setTypeface(null, Typeface.NORMAL);
                }
                break;
            case R.id.checkbox_brown:
                if (checked){
                    cb_brown.setTypeface(cb_red.getTypeface(), Typeface.BOLD_ITALIC);
                }
                else{
                    cb_brown.setTypeface(null, Typeface.NORMAL);
                }
                break;
            case R.id.checkbox_yellow:
                if (checked){
                    cb_yellow.setTypeface(cb_red.getTypeface(), Typeface.BOLD_ITALIC);
                }
                else{
                    cb_yellow.setTypeface(null, Typeface.NORMAL);
                }
                break;
            case R.id.checkbox_crimson:
                if (checked){
                    cb_crimson.setTypeface(cb_red.getTypeface(), Typeface.BOLD_ITALIC);
                }
                else{
                    cb_crimson.setTypeface(null, Typeface.NORMAL);
                }
                break;
            case R.id.checkbox_indigo:
                if (checked){
                    cb_indigo.setTypeface(cb_red.getTypeface(), Typeface.BOLD_ITALIC);
                }
                else{
                    cb_indigo.setTypeface(null, Typeface.NORMAL);
                }
                break;
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

2. CheckBox Set Click Listener

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    >
    <TextView
        android:id="@+id/tv_message"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Check the CheckBoxes...."
        />
    <CheckBox

        android:id="@+id/checkbox_pink"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Pink"
        android:layout_below="@id/tv_message"
        />
    <CheckBox
        android:id="@+id/checkbox_magenta"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Magenta"
        android:layout_below="@id/checkbox_pink"
        />
</RelativeLayout>
MainActivity.java (Partial code)

@Override
protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

 //start the CheckBox listener coding...
 final TextView tvMessage = (TextView) findViewById(R.id.tv_message);
 final CheckBox cbPink = (CheckBox) findViewById(R.id.checkbox_pink);
 final CheckBox cbMagenta = (CheckBox) findViewById(R.id.checkbox_magenta);

 //set an OnClickListener for CheckBox Pink
 cbPink.setOnClickListener(new OnClickListener(){
  @Override
  //set a click event for CheckBox Pink
  public void onClick(View v){
   if(cbPink.isChecked())
   {
    //If the CheckBox Pink is checked then inform the user
    tvMessage.setText("You clicked and checked the CheckBox: " + cbPink.getText());
   }
   else
   {
    //Inform the user that CheckBox Pink is unchecked now by last click
    tvMessage.setText("You clicked and unchecked the CheckBox: " + cbPink.getText());
   }
  }
 });

 cbMagenta.setOnClickListener(new OnClickListener(){
    @Override
  public void onClick(View v){
      if(cbMagenta.isChecked()){
       tvMessage.setText("You clicked and checked the CheckBox: " + cbMagenta.getText());
      }
      else
      {
       tvMessage.setText("You clicked and unchecked the CheckBox: " + cbMagenta.getText());
      }
     }
 });
}
MainActivity.java (Additional imported classes)

import android.view.View;
import android.widget.CheckBox;
import android.view.View.OnClickListener;
import android.widget.TextView;

3. CheckBox OnCheckedChangeListener

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    >
    <TextView
        android:id="@+id/tv_message"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Check the CheckBoxes...."
        />
    <CheckBox
        android:id="@+id/checkbox_orange"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Orange"
        android:layout_below="@id/tv_message"
        />
    <CheckBox
        android:id="@+id/checkbox_lavender"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Lavender"
        android:layout_below="@id/checkbox_orange"
        />
</RelativeLayout>
MainActivity.java (Partial code)

@Override
protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

 //start the CheckBox Checked Change Listener coding...
 final TextView tvMessage = (TextView) findViewById(R.id.tv_message);
 final CheckBox cbOrange = (CheckBox) findViewById(R.id.checkbox_orange);
 final CheckBox cbLavender = (CheckBox) findViewById(R.id.checkbox_lavender);

 //set a CheckedChangeListener for CheckBox Orange
 cbOrange.setOnCheckedChangeListener(new OnCheckedChangeListener(){
    @Override
  public void onCheckedChanged(CompoundButton cb, boolean isChecked){
   if(isChecked)
   {
    //If Orange CheckBox is checked by current click
    tvMessage.setText("You checked the CheckBox Orange");
   }
     else
   {
    //If Orange CheckBox is unchecked by current click
    tvMessage.setText("You unchecked the CheckBox Orange");
   }
    }
 });

 //set another CheckedChangeListener for CheckBox Lavender
 cbLavender.setOnCheckedChangeListener(new OnCheckedChangeListener(){
    @Override
  public void onCheckedChanged(CompoundButton cb, boolean isChecked){
     if(isChecked)
     {
      tvMessage.setText("You checked the CheckBox Lavender");
     }
     else
     {
      tvMessage.setText("You unchecked the CheckBox Lavender");
     }
    }
 });
}
MainActivity.java (Additional imported classes)

import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;

4. CheckBox Custom Style

res/layout/activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    >
    <CheckBox
        android:id="@+id/checkbox_default"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Default Style"
        />
    <CheckBox
        android:id="@+id/checkbox_light_salmon"
        android:text="Light Salmon"
        android:layout_below="@id/checkbox_default"
        style="@style/CheckBoxCustomStyle"
        />
    <CheckBox
        android:id="@+id/checkbox_sea_green"
        android:text="Sea Green"
        android:layout_below="@id/checkbox_light_salmon"
        style="@style/CheckBoxCustomStyle"
        />
    <CheckBox
        android:id="@+id/checkbox_light_yellow"
        android:text="Light Yellow"
        android:layout_below="@id/checkbox_sea_green"
        style="@style/CheckBoxCustomStyle"
        />
</RelativeLayout>
res/values/styles.xml

<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Base application theme. -->
    <!--
        //Android Latest Material Theme
        @android:style/Theme.Material (dark version)
        @android:style/Theme.Material.Light (light version)
        @android:style/Theme.Material.Light.DarkActionBar
        //require minSdkVersion =>21
    -->
    <style name="AppTheme" parent="@android:style/Theme.Material.Light">
        <!-- Customize your theme here. -->
    </style>

    <style name="CheckBoxCustomStyle" parent="@android:style/Widget.CompoundButton.CheckBox">
        <item name="android:background">@drawable/checkbox_bg</item>
        <item name="android:textColor">#800080</item>
        <item name="android:layout_margin">3dp</item>
        <item name="android:paddingLeft">10dp</item>
        <item name="android:paddingRight">15dp</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_width">wrap_content</item>
        <item name="android:button">@drawable/checkbox_custom_states</item>
    </style>
</resources>
res/drawable/checkbox_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#dbe7f3"/>
            <stroke android:color="#d2e0ef" android:width="1dp"/>
            <corners android:bottomRightRadius="10dp"/>
        </shape>
    </item>
</selector>
res/drawable/checkbox_custom_states.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_checked="true"
        android:drawable="@drawable/checkbox_checked_state"
        />
    <item android:drawable="@drawable/checkbox_unchecked_state"/>
</selector>
res/drawable/checkbox_checked_state.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#778899"/>
            <size android:width="20dp" android:height="20dp"/>
            <stroke android:color="#8fb5db" android:width="1dp"/>
            <corners android:radius="2dp"/>
        </shape>
    </item>
    <item android:left="2dp" android:top="2dp" android:right="2dp" android:bottom="2dp">
        <shape android:shape="rectangle">
            <solid android:color="#B0C4DE"/>
            <stroke android:color="#778899" android:width="1dp"/>
            <corners android:radius="2dp"/>
        </shape>
    </item>
</layer-list>
res/drawable/checkbox_unchecked_state.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:right="5dp" android:top="5dp">
        <shape android:shape="rectangle">
            <solid android:color="#778899"/>
            <size android:width="20dp" android:height="20dp"/>
            <stroke android:color="#3f4e5e" android:width="1dp"/>
            <corners android:radius="2dp"/>
        </shape>
    </item>
</selector>
More android examples

Popular posts from this blog

How to use NumberPicker in Android

Table of contentsNumberPicker ExamplesetOnValueChangedListeneronValueChange()setWrapSelectorWheel()setMinValue()setMinValue()setMaxValue()NumberPicker with String ArraysetDisplayedValues()String Array1. NumberPicker Example activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/rl" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" tools:context=".MainActivity" android:background="#ffffff" > <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="25dp" android:text="Select a number..." /> <NumberPicker android:id="@+id/np" …

TextView new line (multiline) in android

TextView new line (multiline) TextView display text on android app. by default, TextView show text on a single line, and if it is long then TextView take more lines to display its text. android developers can generate a new line on TextView both programmatically and syntactically. android developers can make a multiline TextView without splitting text to multiline by android:minLines attribute.

the following android example code demonstrate us how can we syntactically create a new line on TextView widget by xml layout file and string resource file.

the simplest way to create a new line on TextView is android:text attribute. android:text attribute allow us to display text on android app. we can add a simple '\n' to TextView text where we want to start a new line. in this way we can create a multiline TextView widget in android app. we can assign android:text attribute value by this way android:text="Line1 \n Line2 \n Line3" for a TextView widget. this value will…

How to change TextView font size in android

TextView font size TextView widget display text on android application. we can set or change TextView font size statically by declarative syntax in xml layout file or programmatically at run time in java file. even we can use an xml file source to define font size.

the following example code demonstrate us how can we define TextView font size in xml layout file and how can we uses dimens.xml to reference font size. in this example we did not changes any coding in java file, so here we only include the layout xml file and dimens.xml file. activity_main.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:layout_margin="25dp" tools:context=".MainActivity" > <TextView android:id=&…