Saturday, 21 July 2012

Android Checkbox Tutorial


Introduction of Android Checkbox Control



Android provides checkbox functionality. Using this control we can provide multiple choice to users.

How to define checkbox control

Android use seperate file for layout. This file stored in android res/layout directory.

syntex :
 <CheckBox
        android:id="@+id/chkandroid"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Android"/>

 
Above syntex define textbox with following properties
  • android:id a unique id provided.
  • android:layout_width this property is used to define width.
  • android:layout_height this property is used to define height.
set OnClickListener for checkbox. We need to set it manually.
How to set OnClickListener
  • First identify your checkbox.
     Syntex :
     
     chkandroid = (CheckBox) findViewById(R.id.chkandroid);
     
  • Then set event to this control
    chkandroid.setOnClickListener(new OnClickListener() {
     
       @Override
       public void onClick(View arg0) {
                    write your code
       }
     
      });
     
Example
  1. Make layout file(main.xml) which contains a checkbox. If we check on checkbox it display a message.

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
     
     <CheckBox
            android:id="@+id/chkandroid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Android"/>
            
     </LinearLayout>
    
  2. Then apply onclick event

    public class MyAndroidAppActivity extends Activity {
     
        private CheckBox chkandroid;
     @Override
     public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
            addListenerOnCheckbox();
     }
        public void addListenerOnCheckbox() {
     
     chkandroid = (CheckBox) findViewById(R.id.chkandroid);
     
     chkandroid.setOnClickListener(new OnClickListener() {
     
       @Override
       public void onClick(View v) {
                    //is chkIos checked?
      if (((CheckBox) v).isChecked()) 
      {
       Toast.makeText(this,"checked",Toast.LENGTH_LONG).show();
      }
      else
      {
          Toast.makeText(this,"Unchecked",Toast.LENGTH_LONG).show();
      }
     
       }
     });
     
      }
    }
    
    
  3. Output : 
                

1 comment: