Objective:
1. Learn how to create a CheckBox in Android
2. Master common attributes of CheckBox
3. Understand the events (listener) for changing the selected status of the CheckBox)
CheckBox introduction:
Like a Button, CheckBox is also an old control. It has the advantage that you do not need to enter specific information, just click, the disadvantage is that there are only two situations: "yes" and "no". However, we often use this feature to obtain user information.
For example, in an identity form, it is unreasonable for a user to fill in "is married" or "no". The ideal scenario is to use the following controls:
Selected status:
Create a CheckBox layout using the methods I used in the Button Tutorial:
Copy codeThe Code is as follows: <CheckBox
Android: id = "@ + id/cb"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: checked = "false"
Android: text = "married"
> </CheckBox>
Obviously, the Checked attribute is one of the most important attributes of the CheckBox. There are three ways to change it:
1. Declaration in XML 2. Dynamic code change 3. User touch
Its changes will trigger the OnCheckedChange event, and you can use the OnCheckedChangeListener listener to listen to this event. If you are not familiar with the listener, you can first learn what I wrote
Android control series Button. If you are not familiar with how to obtain controls in code, you can learn about the XML static resources of the Android control series I wrote.
The specific anonymous listening method code is as follows:
Copy codeThe Code is as follows: // get the CheckBox instance
CheckBox cb = (CheckBox) this. findViewById (R. id. cb );
// Bind the listener
Cb. setOnCheckedChangeListener (new OnCheckedChangeListener (){
@ Override
Public void onCheckedChanged (CompoundButton arg0, boolean arg1 ){
// TODO Auto-generated method stub
Toast. makeText (MyActivity. this,
Arg1? "Selected": "deselected", Toast. LENGTH_LONG). show ();
}
});
Summary:
This article uses the simplest example to illustrate how to use CheckBox in Android and monitor its selected status change events to implement the business logic you need.