Android CheckBox Control

Advertisements


A CheckBox is an on/off switch that can be toggled by the user. You should use check-boxes when presenting users with a group of selectable options that are not mutually exclusive.

CheckBox Attributes

Following are the important attributes related to CheckBox control. You can check Android official documentation for complete list of attributes and related methods which you can use to change these attributes are run time.

Inherited from android.widget.TextView Class:

AttributeDescription
android:autoTextIf set, specifies that this TextView has a textual input method and automatically corrects some common spelling errors.
android:drawableBottomThis is the drawable to be drawn below the text.
android:drawableRightThis is the drawable to be drawn to the right of the text.
android:editableIf set, specifies that this TextView has an input method.
android:textThis is the Text to display.

Inherited from android.view.View Class:

AttributeDescription
android:backgroundThis is a drawable to use as the background.
android:contentDescriptionThis defines text that briefly describes content of the view.
android:idThis supplies an identifier name for this view,
android:onClickThis is the name of the method in this View's context to invoke when the view is clicked.
android:visibilityThis controls the initial visibility of the view.

Example

This example will take you through simple steps to show how to create your own Android application using Linear Layout and CheckBox.

StepDescription
1You will use Eclipse IDE to create an Android application and name it as GUIDemo6 under a package com.example.guidemo6 as explained in the Hello World Example chapter.
2Modify src/MainActivity.java file to add a click event.
2Modify the default content of res/layout/activity_main.xml file to include Android UI control.
3Define required constants in res/values/strings.xml file
4Run the application to launch Android emulator and verify the result of the changes done in the application.

Following is the content of the modified main activity file src/com.example.guidemo5/MainActivity.java. This file can include each of the fundamental lifecycle methods.

package com.example.guidemo6;

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

public class MainActivity extends Activity {

   private CheckBox chk1, chk2, chk3;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      // 3 methods
      addListenerOnCheck1();
      addListenerOnCheck2();
      addListenerOnCheck3();
   }

   // method for CheckBox1 - Java
   private void addListenerOnCheck1() {
      chk1 = (CheckBox) findViewById(R.id.checkBox1);
      chk2 = (CheckBox) findViewById(R.id.checkBox2);
      chk3 = (CheckBox) findViewById(R.id.checkBox3);
      chk2.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

          StringBuffer result = new StringBuffer();
          result.append("Java Selection : ").append
          (chk1.isChecked());
          result.append("\nPerl Selection : ").append
          (chk2.isChecked());
          result.append("\nPython Selection :").append
          (chk3.isChecked());
			
		Toast.makeText(MainActivity.this, result.toString(), 
           Toast.LENGTH_LONG).show();
        }
     });
		
    }

   // method for CheckBox2 - Perl
   private void addListenerOnCheck2() {

      chk1 = (CheckBox) findViewById(R.id.checkBox1);
      chk2 = (CheckBox) findViewById(R.id.checkBox2);
      chk3 = (CheckBox) findViewById(R.id.checkBox3);
      chk3.setOnClickListener(new OnClickListener() {
		
		@Override
		public void onClick(View v) {

             StringBuffer result = new StringBuffer();
             result.append("Java Selection : ").append  
             (chk1.isChecked());
             result.append("\nPerl Selection : ").append
             (chk2.isChecked());
             result.append("\nPython Selection :").append
             (chk3.isChecked());

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

	/* method for CheckBox3 - Python */
	private void addListenerOnCheck3() {
		// TODO Auto-generated method stub
	    chk1 = (CheckBox) findViewById(R.id.checkBox1);
	    chk2 = (CheckBox) findViewById(R.id.checkBox2);
	    chk3 =  (CheckBox) findViewById(R.id.checkBox3);
	    
		chk1.setOnClickListener(new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			 
			StringBuffer result = new StringBuffer();
			 result.append("Java Selection : ").append(chk1.isChecked());
			 result.append("\nPerl Selection : ").append(chk2.isChecked());
			 result.append("\nPython Selection :").append(chk3.isChecked());
			
			 Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_LONG).show();
			 
		   }
		   });
		
	}

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


Following will be the content of res/layout/activity_main.xml file:

<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/example_checkbox" />

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="88dp"
        android:text="@string/check_one" />

    <CheckBox
        android:id="@+id/checkBox2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/checkBox1"
        android:layout_below="@+id/checkBox1"
        android:layout_marginTop="22dp"
        android:text="@string/check_two" />

    <CheckBox
        android:id="@+id/checkBox3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/checkBox2"
        android:layout_marginTop="24dp"
        android:text="@string/check_three" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/checkBox1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="39dp"
        android:text="@string/example_question" />

</RelativeLayout>

Following will be the content of res/values/strings.xml to define these new constants:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">GUIDemo6</string>
    <string name="action_settings">Settings</string>
    <string name="example_checkbox">Example showing CheckBox Control</string>
    <string name="check_one">JAVA</string>
    <string name="check_two">PERL</string>
    <string name="check_three">PYTHON</string>
    <string name="example_question">Worked on following Languages-</string>	

</resources>

Following is the default content of AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.guidemo6"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.guidemo5.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Let's try to run your GUIDemo6 application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:

Android CheckBox Control

The following screen will appear after CheckBox1 i.e Java is clicked:

Android CheckBox Control

The following screen will appear after CheckBox3 i.e Python is clicked, now it will appear for both Java(previous selection) and Perl:

Android CheckBox Control

Exercise:

I will recommend to try above example with different attributes of CheckBox in Layout XML file as well at programming time to have different look and feel of the CheckBox. Try to make it editable, change to font color, font family, width, textSize etc and see the result. You can also try above example with multiple CheckBox controls in one activity.



Advertisements
Advertisements