Android CheckBox

Android CheckBox button has two state , either it can be checked or unchecked. Checkbox can be used in multiple way for example, it can be used to know the hobby of the user,multi choice selection, activate/deactivate the specific action etc. Android CheckBox class is the subclass of CompoundButton class.

Android CheckBox Example


XML Layout for Checkbox Example

Take few checkboxes in Relative Layout and a Button to get the state of checkboxes.

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="dzone.jaipur.myapp1.MainActivity" >

    <CheckBox  
        android:id="@+id/checkBox1"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignParentLeft="true"  
        android:layout_alignParentTop="true"  
        android:text="Pizza" />

    <CheckBox  
        android:id="@+id/checkBox2"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignParentTop="true"  
        android:layout_toRightOf="@+id/checkBox1"  
        android:text="Coffe"/>

   <CheckBox  
        android:id="@+id/checkBox3"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignParentTop="true"  
        android:layout_toRightOf="@+id/checkBox2"  
        android:text="Burger" />

   <Button  
        android:id="@+id/button1"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_below="@+id/checkBox2"  
        android:layout_marginTop="32dp"  
        android:layout_toLeftOf="@+id/checkBox3"  
        android:text="Order"/>

  </RelativeLayout>

Noe in your MainActivty Class write code to check the checkboxes state and give desired output.
Every Checkbox has a method named "isChecked()" which return the boolean result of checkbox state means it return 'true' when it's in On or checked and 'false' when get off.


public class MainActivity extends AppCompatActivity {
    
	CheckBox pizza,coffe,burger;  
    Button buttonOrder; 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		 addListenerOnButtonClick();  

		
	}
	public void addListenerOnButtonClick(){  
    //Getting instance of CheckBoxes and Button from the activty_main.xml file  
    pizza=(CheckBox)findViewById(R.id.checkBox1);  
    coffe=(CheckBox)findViewById(R.id.checkBox2);  
    burger=(CheckBox)findViewById(R.id.checkBox3);  
    buttonOrder=(Button)findViewById(R.id.button1);  
  
    //Applying the Listener on the Button click  
    buttonOrder.setOnClickListener(new OnClickListener(){  
  
        @Override  
        public void onClick(View view) {  
            int totalamount=0;  
            StringBuilder result=new StringBuilder();  
            result.append("Selected Items:");  
            if(pizza.isChecked()){  
                result.append("\nPizza 100Rs");  
                totalamount+=100;  
            }  
            if(coffe.isChecked()){  
                result.append("\nCoffe 50Rs");  
                totalamount+=50;  
            }  
            if(burger.isChecked()){  
                result.append("\nBurger 120Rs");  
                totalamount+=120;  
            }  
            result.append("\nTotal: "+totalamount+"Rs");  
            //Displaying the message on the toast  
            Toast.makeText(getApplicationContext(), result.toString(), Toast.LENGTH_LONG).show();  
        }  
          
    });  

	

}


Now Run the Application and select the item of your choice,After button click you will get Total Amount of selected items.



Attributes of Android CheckBox

id :


id is an attribute used to uniquely give an identity to check box.You can define this like..
android:id="@+id/MyCheckBox"

checked :


checked attribute used to set the default state of checkbox through xml design.We can assign a boolean value to set the state of checked or unchecked.You have to assign true for check and false for uncheck.

<CheckBox
    android:id="@+id/MyCheckBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="My CheckBox" 
    android:checked="true"/> <!--set the default state of the check box-->

Dynamically setting the Checkbox state

To set or change the checkbox state by programming in java file we should use setChecked() function.

//get the refrence of checkbox
CheckBox myCheck1 = (CheckBox) findViewById(R.id.MyCheckBox);

// set the state of a check box
myCheck1.setChecked(true);

text :

text attribute used to set the caption on checkbox.We can set it in xml Layout or can also be changed at run time by java file.

>CheckBox
    android:id="@+id/simpleCheckBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="true"
    android:text="Text Attribute Of Check Box"> >--displayed text of the check box-->

Assigning Checkbox Text in java class

To set or change the text by programming in java file we should use setText() method.

//get the refrence of checkbox
CheckBox myCheck1 = (CheckBox) findViewById(R.id.MyCheckBox);

// set the state of a check box
myCheck1.setText("Want to Join Android Course at D Zone");

TextColor:

TextColor attribute is used to set the text color of a check box. Color value is in form of "#argb", "#rgb", "#rrggbb", or "#aarrggbb".

<CheckBox
    android:id="@+id/MyCheckBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Sample Text"
    android:textColor="#FF6600" 
    android:checked="true"/> <!-- red color for the text of check box-->

TextSize:

TextSize attribute is used to set the size of text of a check box. We can set the text size in sp(scale independent pixel) or dp(density pixel).

<CheckBox
    android:id="@+id/simpleCheckBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Text size Attribute Of Check Box"
    android:textColor="#00f"
    android:checked="false"
    android:textSize="20sp"><--set Text Size of text in CheckBox-->

TextStyle:

TextStyle attribute is used to set the text style of the text of a check box. The possible text styles are bold, italic and normal. If we need to use two or more styles for a text view then "|" operator is used for that.

<CheckBox
    android:id="@+id/simpleCheckBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Text Style Attribute Of Check Box"
    android:textColor="#44f"
    android:textSize="20sp"
    android:checked="false"
    android:textStyle="bold|italic">

Background:

background attribute is used to set the background of a check box. We can set a color or a drawable Image in the background of a check box.

< android:id="@+id/simpleCheckBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Text size Attribute Of Check Box"
    android:textColor="#fff"
    android:textSize="20sp"
    android:textStyle="bold|italic"
    android:checked="true"
    android:background="#000" > <black background for the background of check box >

padding:

padding attribute is used to set the padding from left, right, top or bottom.

< CheckBox
    android:id="@+id/simpleCheckBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Padding Attribute Of Check Box"
    android:textColor="#44f" 
    android:textSize="20sp"
    android:textStyle="bold|italic"
    android:checked="false"
    android:padding="30dp"> <30dp padding from all side's-->

Hope these notes will be helpful to you for understanding Android Chackbox.