Switch
控件是 Android 中用来表示开关状态的一个 UI 元素,它继承自 CompoundButton
,这意味着它也继承了 Button
的一些特性,比如事件处理等。Switch
控件主要用于二进制选择,即开和关两种状态。下面我将结合源码分析 Switch
的实现原理。
1. Switch 类定义
Switch
类定义如下:
1public class Switch extends CompoundButton {
2 // ...
3}
2. 构造函数
Switch
的构造函数如下:
1public Switch(Context context) {
2 this(context, null);
3}
4
5public Switch(Context context, AttributeSet attrs) {
6 this(context, attrs, android.R.attr.switchStyle);
7}
8
9public Switch(Context context, AttributeSet attrs, int defStyleAttr) {
10 super(context, attrs, defStyleAttr);
11 initSwitch();
12}
构造函数中调用了 initSwitch
方法来初始化 Switch
的属性。
3. 初始化
初始化方法会设置默认属性,并读取自定义属性。
1void initSwitch() {
2 // ...
3 TypedArray a = getC