CheckBox
是 Android 中的一个常用控件,用于实现复选框的功能。它继承自 CompoundButton
,后者又继承自 Button
。CheckBox
可以用来表示一个布尔值的选择状态,通常用于收集用户的选择,例如在表单中选择多个选项。
接下来,我们将结合源码来分析 CheckBox
的实现原理。
1. CheckBox 类定义
CheckBox
类定义如下:
1public class CheckBox extends CompoundButton {
2 // ...
3}
CheckBox
继承自 CompoundButton
,因此它具备 CompoundButton
的所有功能,并且可以显示文本和图标。
2. 构造函数
CheckBox
的构造函数如下:
1public CheckBox(Context context) {
2 this(context, null);
3}
4
5public CheckBox(Context context, AttributeSet attrs) {
6 this(context, attrs, android.R.attr.checkboxStyle);
7}
8
9public CheckBox(Context context, AttributeSet attrs, int defStyleAttr) {
10 super(context, attrs, defStyleAttr);
11 init(context, attrs, defStyleAttr, 0);
12}
<