java.lang.Object -> android.view.View -> android.widget.TextView -> android.widget.Button -> android.widget.CompoundButton -> android.widget.CheckBox.
A checkbox is a specific type of two-states button that can be either checked or unchecked. It has following properties:
isChecked() Determines if the check box has been checked.
setChecked() Forces the check box into a checked or unchecked state.
toggle() Toggles the check box as if the user checked it.
We can register a listener object (in this case, an instance of OnCheckedChangeListener) to be notified when the state of the check box changes.
Let us look at the example, "MyCheckBox.java."package com.bogotobogo.MyCheckBox;
import android.app.Activity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
public class MyCheckBox extends Activity
implements CompoundButton.OnCheckedChangeListener{
CheckBox cb;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
cb = (CheckBox)findViewById(R.id.checkbox);
cb.setOnCheckedChangeListener(this);
}
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if(isChecked){
cb.setText("state: checked");
}
else {
cb.setText("state: unchecked");
}
}
}
Note that the activity serves as its own listener for check box state changes, since it implements the OnCheckedChangeListener interface (via cb.setOnCheckedChangeListener(this)). The callback for the listener is onCheckedChanged(), which receives the check box whose state has changed. Then, we update the text of the check box to indicate what the actual box contains.
The layout file is:
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
android:layout_height="wrap_content"
android:text="state: unchecked"
/>
Run this application and the result should look like this:
Full List of Android Tutorials
25. Activity Life Cycle
24. Media
23. HTTP Internet Connection
22. Threads
21. Content Provider
20. Notification and Service
19. Animation - Frame By Frame, Layout, and View
18. Manifest
17. Map View
16. Preferences
15. Configuring Rotation
14. On Notepad Examples
13. Intent
12. Activity Testing
11. Android JUnit Test
10. Menus
9. TabWidget, Flipper, and SlidingDrawer
8. DatePicker, TimePicker, and Clocks
7. Advanced ListView Widget
6. ListView, Spinner
5. Layouts
4. User Interface
3. Back to Hello World Again
2. Hello World
1. Introduction
No comments:
Post a Comment