发布时间:2025-12-11 00:48:39 浏览次数:1
CheckBox和CompoundButton都是Android中的View控件,它们都继承自Button类,因此它们具有Button的一些属性和方法。下面分别对CheckBox和CompoundButton的源码进行解析。
CheckBox源码解析:CheckBox是一个可选的标志,可以用于表示选中或未选中状态。CheckBox继承自CompoundButton类。以下是CheckBox的部分源码解析:
public class CheckBox extends CompoundButton {// 构造方法public CheckBox(Context context) {this(context, null);}public CheckBox(Context context, AttributeSet attrs) {this(context, attrs, R.attr.checkboxStyle);}public CheckBox(Context context, AttributeSet attrs, int defStyleAttr) {this(context, attrs, defStyleAttr, 0);}public CheckBox(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {super(context, attrs, defStyleAttr, defStyleRes);}}在构造方法中,CheckBox调用了父类CompoundButton的构造方法,传递了相应的参数。CompoundButton是一个抽象类,它继承自Button类,并实现了Checkable接口。CompoundButton中定义了一些与选择状态相关的方法和属性,例如setChecked()、isChecked()等。
CompoundButton源码解析:CompoundButton是一个抽象类,它继承自Button类,并实现了Checkable接口。以下是CompoundButton的部分源码解析:
public abstract class CompoundButton extends Button implements Checkable {// 选中状态改变监听器private OnCheckedChangeListener mOnCheckedChangeListener;// 按钮的选中状态private boolean mChecked;// 是否正在设置选中状态private boolean mBroadcasting;// 构造方法public CompoundButton(Context context) {this(context, null);}public CompoundButton(Context context, AttributeSet attrs) {this(context, attrs, R.attr.buttonStyle);}public CompoundButton(Context context, AttributeSet attrs, int defStyleAttr) {this(context, attrs, defStyleAttr, 0);}public CompoundButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {super(context, attrs, defStyleAttr, defStyleRes);// 初始化选中状态if (attrs != null) {TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CompoundButton, defStyleAttr, defStyleRes);boolean checked = a.getBoolean(R.styleable.CompoundButton_android_checked, false);setChecked(checked);a.recycle();}}// 设置选中状态public void setChecked(boolean checked) {if (mChecked != checked) {mChecked = checked;refreshDrawableState();// 通知选中状态改变if (!mBroadcasting) {mBroadcasting = true;if (mOnCheckedChangeListener != null) {mOnCheckedChangeListener.onCheckedChanged(this, mChecked);}mBroadcasting = false;}}}// 获取选中状态public boolean isChecked() {return mChecked;}// 添加选中状态改变监听器public void setOnCheckedChangeListener(OnCheckedChangeListener listener) {mOnCheckedChangeListener = listener;}// 选中状态改变监听器接口public interface OnCheckedChangeListener {void onCheckedChanged(CompoundButton buttonView, boolean isChecked);}}CompoundButton中定义了一些方法和属性,用于设置和获取选中状态,以及添加选中状态改变监听器。在构造方法中,CompoundButton会根据传入的属性初始化选中状态。setChecked()方法用于设置选中状态,并在状态改变时通知监听器。isChecked()方法用于获取当前的选中状态。
总结:
CheckBox是一个可选的标志,继承自CompoundButton类,而CompoundButton是一个抽象类,继承自Button类,并实现了Checkable接口。CompoundButton中定义了一些与选择状态相关的方法和属性,以及选中状态改变的监听器接口。