Check the usage of CheckBox in an Android activity

CheckBox:

It is a widget which takes any of the two states – checked or unchecked.

Let’s see the XML code first and then move on to the program code.

XML code:

<CheckBox         android:id="@+id/check"         android:text="OK/CANCEL"         android:layout_width="wrap_content"         android:layout_height="wrap_content"  />

This is how the screen looks:

The code goes here:

CheckBox ck=(CheckBox)findViewById(R.id.check);
ck.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(buttonView.isChecked())
{
Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "CANCEL", Toast.LENGTH_LONG).show();
}
}
});

Write the code for what is to be done when the checkbox is in checked and unchecked as shown inside the callback method onCheckedChanged(CompoundButton buttonView, boolean isChecked).Here, in my example a Toast will be displayed when checked or unchecked.

This is how the output looks:

Advertisements

, , , ,

  1. #1 by dvc hawaii aulani on February 25, 2012 - 7:26 pm

    This valuable write-up has been so useful to me personally that I saved your website link, https://androiddesk.wordpress.com/2012/01/26/check-the-usage-of-checkbox-in-an-android-activity/ at Google.

    • #2 by Deepthi G on February 25, 2012 - 8:06 pm

      Hey

      Thanks for those kind words.. Keep reading.. Enjoy!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: