Android 4.0 Switch 控件用源代码实现

来源:互联网 发布:运动鞋哪些牌子 知乎 编辑:程序博客网 时间:2024/06/08 08:56

最近项目需要,在4.0 以前的版本上实现一个android 4.0 上的Switch控件,上网找了些例子,都不尽如人意。自己动手,丰衣足食。于是便翻看源码,找到4.0源码中Switch实现的方法。照样子实现了一个,基本上跟4.0的效果一样,使用上没有任何差异。
直接上图:
以下是Switch控件实现的源码:

代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
publicclass Switch extendsCompoundButton {...
   publicSwitch(Context context) {
        this(context,null);        mContext = context;
   }
   publicSwitch(Context context, AttributeSet attrs) {
        this(context, attrs, R.attr.switchStyle);        mContext = context;
   }
   publicSwitch(Context context, AttributeSet attrs, intdefStyle) {
        super(context, attrs, defStyle);        mContext = context;        mTextPaint = newTextPaint(Paint.ANTI_ALIAS_FLAG);
        Resources res = getResources();
        mTextPaint.density = res.getDisplayMetrics().density;
TypedArray a = context.obtainStyledAttributes(attrs,                R.styleable.Switch, defStyle,0);        mThumbDrawable = a.getDrawable(R.styleable.Switch_thumb);
        mTrackDrawable = a.getDrawable(R.styleable.Switch_track);
        mTextOn = a.getText(R.styleable.Switch_textOn);
        mTextOff = a.getText(R.styleable.Switch_textOff);
        mThumbTextPadding = a.getDimensionPixelSize(
                R.styleable.Switch_thumbTextPadding,0);
        mSwitchMinWidth = a.getDimensionPixelSize(
                R.styleable.Switch_switchMinWidth,0);
        mSwitchPadding = a.getDimensionPixelSize(
                R.styleable.Switch_switchPadding,0);        intappearance = a.getResourceId(
                R.styleable.Switch_switchTextAppearance,0);
        if(appearance != 0) {
            setSwitchTextAppearance(context, appearance);
        }
        a.recycle();        ViewConfiguration config = ViewConfiguration.get(context);
        mTouchSlop = config.getScaledTouchSlop();
        mMinFlingVelocity = config.getScaledMinimumFlingVelocity();        refreshDrawableState();
        setChecked(isChecked());
   }
   publicvoid setSwitchTextAppearance(Context context, intresid) {
        mContext = context;        TypedArray appearance =
                context.obtainStyledAttributes(resid,
                        R.styleable.TextAppearance);        ColorStateList colors;
        intts;        colors = appearance.getColorStateList(R.styleable.
                TextAppearance_textColor);
        if(colors != null) {
            mTextColors = colors;
        }else{
            mTextColors = getTextColors();
        }        ts = appearance.getDimensionPixelSize(R.styleable.
                TextAppearance_textSize,0);
        if(ts != 0) {
            if(ts != mTextPaint.getTextSize()) {
                mTextPaint.setTextSize(ts);
                requestLayout();
            }
        }        inttypefaceIndex, styleIndex;        typefaceIndex = appearance.getInt(R.styleable.
                TextAppearance_typeface, -1);
        styleIndex = appearance.getInt(R.styleable.
                TextAppearance_textStyle, -1);        setSwitchTypefaceByIndex(typefaceIndex, styleIndex);        appearance.recycle();
   }    privatevoid setSwitchTypefaceByIndex(inttypefaceIndex, intstyleIndex) {
        Typeface tf = null;
        switch(typefaceIndex) {
            caseSANS:
                tf = Typeface.SANS_SERIF;
                break;            caseSERIF:
                tf = Typeface.SERIF;
                break;            caseMONOSPACE:
                tf = Typeface.MONOSPACE;
                break;
        }        setSwitchTypeface(tf, styleIndex);
   }
   publicvoid setSwitchTypeface(Typeface tf, intstyle) {
        if(style > 0) {
            if(tf == null) {
                tf = Typeface.defaultFromStyle(style);
            }else{
                tf = Typeface.create(tf, style);
            }            setSwitchTypeface(tf);
            // now compute what (if any) algorithmic styling is needed
            inttypefaceStyle = tf != null? tf.getStyle() : 0;
            intneed = style & ~typefaceStyle;
            mTextPaint.setFakeBoldText((need & Typeface.BOLD) != 0);
            mTextPaint.setTextSkewX((need & Typeface.ITALIC) != 0? -0.25f : 0);
        }else{
            mTextPaint.setFakeBoldText(false);
            mTextPaint.setTextSkewX(0);
            setSwitchTypeface(tf);
        }
   }
   publicvoid setSwitchTypeface(Typeface tf) {
        if(mTextPaint.getTypeface() != tf) {
            mTextPaint.setTypeface(tf);            requestLayout();
            invalidate();
        }
   }
   publicCharSequence getTextOn() {
        returnmTextOn;
   }
   publicvoid setTextOn(CharSequence textOn) {
        mTextOn = textOn;
        requestLayout();
   }
   publicCharSequence getTextOff() {
        returnmTextOff;
   }
   publicvoid setTextOff(CharSequence textOff) {
        mTextOff = textOff;
        requestLayout();
   }    @Override
   publicvoid onMeasure(intwidthMeasureSpec, intheightMeasureSpec) {
        finalint widthMode = MeasureSpec.getMode(widthMeasureSpec);
        finalint heightMode = MeasureSpec.getMode(heightMeasureSpec);
        intwidthSize = MeasureSpec.getSize(widthMeasureSpec);
        intheightSize = MeasureSpec.getSize(heightMeasureSpec);        if(mOnLayout == null) {
            mOnLayout = makeLayout(mTextOn);
        }
        if(mOffLayout == null) {
            mOffLayout = makeLayout(mTextOff);
        }        mTrackDrawable.getPadding(mTempRect);
        finalint maxTextWidth = Math.max(mOnLayout.getWidth(), mOffLayout.getWidth());
        finalint switchWidth = Math.max(mSwitchMinWidth,
                maxTextWidth * 2+ mThumbTextPadding * 4+ mTempRect.left + mTempRect.right);
        finalint switchHeight = mTrackDrawable.getIntrinsicHeight();        mThumbWidth = maxTextWidth + mThumbTextPadding *2;        switch(widthMode) {
            caseMeasureSpec.AT_MOST:
                widthSize = Math.min(widthSize, switchWidth);
                break;            caseMeasureSpec.UNSPECIFIED:
                widthSize = switchWidth;
                break;            caseMeasureSpec.EXACTLY:
                // Just use what we were given
                break;
        }        switch(heightMode) {
            caseMeasureSpec.AT_MOST:
                heightSize = Math.min(heightSize, switchHeight);
                break;            caseMeasureSpec.UNSPECIFIED:
                heightSize = switchHeight;
                break;            caseMeasureSpec.EXACTLY:
                // Just use what we were given
                break;
        }        mSwitchWidth = switchWidth;
        mSwitchHeight = switchHeight;        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        finalint measuredHeight = getMeasuredHeight();
        if(measuredHeight < switchHeight) {
            setMeasuredDimension(getMeasuredWidth(), switchHeight);
        }
   }
   @Override
   publicboolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
        Log.d("SvenDebug","dispatchPopulateAccessibilityEvent");
        populateAccessibilityEvent(event);        returnfalse;
   }    publicvoid populateAccessibilityEvent(AccessibilityEvent event) {
        if(isChecked()) {
            CharSequence text = mOnLayout.getText();
            if(TextUtils.isEmpty(text)) {
                text = mContext.getString(R.string.switch_on);
            }
            event.getText().add(text);
        }else{
            CharSequence text = mOffLayout.getText();
            if(TextUtils.isEmpty(text)) {
                text = mContext.getString(R.string.switch_off);
            }
            event.getText().add(text);
        }
   }    privateLayout makeLayout(CharSequence text) {
        returnnew StaticLayout(text, mTextPaint,
                (int) Math.ceil(Layout.getDesiredWidth(text, mTextPaint)),
                Layout.Alignment.ALIGN_NORMAL,1.f,0,true);
   }
   privateboolean hitThumb(floatx, floaty) {
        mThumbDrawable.getPadding(mTempRect);
        finalint thumbTop = mSwitchTop - mTouchSlop;
        finalint thumbLeft = mSwitchLeft + (int) (mThumbPosition + 0.5f) - mTouchSlop;
        finalint thumbRight = thumbLeft + mThumbWidth +
                mTempRect.left + mTempRect.right + mTouchSlop;
        finalint thumbBottom = mSwitchBottom + mTouchSlop;
        returnx > thumbLeft && x < thumbRight && y > thumbTop && y < thumbBottom;
   }    @Override
   publicboolean onTouchEvent(MotionEvent ev) {
        mVelocityTracker.addMovement(ev);
        finalint action = ev.getActionMasked();
        switch(action) {
            caseMotionEvent.ACTION_DOWN: {
                Log.d("SvenDebug","MotionEvent.ACTION_DOWN");
                finalfloat x = ev.getX();
                finalfloat y = ev.getY();
                if(isEnabled() && hitThumb(x, y)) {
                    mTouchMode = TOUCH_MODE_DOWN;
                    mTouchX = x;
                    mTouchY = y;
                }
                break;
            }            caseMotionEvent.ACTION_MOVE: {
                switch(mTouchMode) {
                    caseTOUCH_MODE_IDLE:
                        // Didn't target the thumb, treat normally.
                        break;                    caseTOUCH_MODE_DOWN: {
                        finalfloat x = ev.getX();
                        finalfloat y = ev.getY();
                        if(Math.abs(x - mTouchX) > mTouchSlop ||
                                Math.abs(y - mTouchY) > mTouchSlop) {
                            mTouchMode = TOUCH_MODE_DRAGGING;
                            getParent().requestDisallowInterceptTouchEvent(true);
                            mTouchX = x;
                            mTouchY = y;
                            returntrue;
                        }
                        break;
                    }                    caseTOUCH_MODE_DRAGGING: {
                        Log.d("SvenDebug","TOUCH_MODE_DRAGGING");
                        finalfloat x = ev.getX();
                        finalfloat dx = x - mTouchX;
                        floatnewPos = Math.max(0,
                                Math.min(mThumbPosition + dx, getThumbScrollRange()));
                        if(newPos != mThumbPosition) {
                            mThumbPosition = newPos;
                            mTouchX = x;
                            invalidate();
                        }
                        returntrue;
                    }
                }
                break;
            }            caseMotionEvent.ACTION_UP:
            caseMotionEvent.ACTION_CANCEL: {
                if(mTouchMode == TOUCH_MODE_DRAGGING) {
                    stopDrag(ev);
                    returntrue;
                }
                mTouchMode = TOUCH_MODE_IDLE;
                mVelocityTracker.clear();
                break;
            }
        }        returnsuper.onTouchEvent(ev);
   }    privatevoid cancelSuperTouch(MotionEvent ev) {
        MotionEvent cancel = MotionEvent.obtain(ev);
        cancel.setAction(MotionEvent.ACTION_CANCEL);
        super.onTouchEvent(cancel);
        cancel.recycle();
   }
   privatevoid stopDrag(MotionEvent ev) {
        mTouchMode = TOUCH_MODE_IDLE;
        booleancommitChange = ev.getAction() == MotionEvent.ACTION_UP && isEnabled();        cancelSuperTouch(ev);        if(commitChange) {
            booleannewState;
            mVelocityTracker.computeCurrentVelocity(1000);
            floatxvel = mVelocityTracker.getXVelocity();
            if(Math.abs(xvel) > mMinFlingVelocity) {
                newState = xvel > 0;
            }else{
                newState = getTargetCheckedState();
            }
            animateThumbToCheckedState(newState);
        }else{
            animateThumbToCheckedState(isChecked());
        }
   }    privatevoid animateThumbToCheckedState(booleannewCheckedState) {
        setChecked(newCheckedState);
   }    privateboolean getTargetCheckedState() {
        returnmThumbPosition >= getThumbScrollRange() / 2;
   }    @Override
   publicvoid setChecked(booleanchecked) {
        super.setChecked(checked);
        mThumbPosition = checked ? getThumbScrollRange() : 0;
        invalidate();
   }    @Override
   protectedvoid onLayout(booleanchanged, intleft, inttop, intright, intbottom) {
        super.onLayout(changed, left, top, right, bottom);        mThumbPosition = isChecked() ? getThumbScrollRange() :0;        intswitchRight = getWidth() - getPaddingRight();
        intswitchLeft = switchRight - mSwitchWidth;
        intswitchTop = 0;
        intswitchBottom = 0;
        switch(getGravity() & Gravity.VERTICAL_GRAVITY_MASK) {
            default:
            caseGravity.TOP:
                switchTop = getPaddingTop();
                switchBottom = switchTop + mSwitchHeight;
                break;            caseGravity.CENTER_VERTICAL:
                switchTop = (getPaddingTop() + getHeight() - getPaddingBottom()) / 2-
                        mSwitchHeight / 2;
                switchBottom = switchTop + mSwitchHeight;
                break;            caseGravity.BOTTOM:
                switchBottom = getHeight() - getPaddingBottom();
                switchTop = switchBottom - mSwitchHeight;
                break;
        }        mSwitchLeft = switchLeft;
        mSwitchTop = switchTop;
        mSwitchBottom = switchBottom;
        mSwitchRight = switchRight;
   }    @Override
   protectedvoid onDraw(Canvas canvas) {
        super.onDraw(canvas);        // Draw the switch
        intswitchLeft = mSwitchLeft;
        intswitchTop = mSwitchTop;
        intswitchRight = mSwitchRight;
        intswitchBottom = mSwitchBottom;        mTrackDrawable.setBounds(switchLeft, switchTop, switchRight, switchBottom);
        mTrackDrawable.draw(canvas);        canvas.save();        mTrackDrawable.getPadding(mTempRect);
        intswitchInnerLeft = switchLeft + mTempRect.left;
        intswitchInnerTop = switchTop + mTempRect.top;
        intswitchInnerRight = switchRight - mTempRect.right;
        intswitchInnerBottom = switchBottom - mTempRect.bottom;
        canvas.clipRect(switchInnerLeft, switchTop, switchInnerRight, switchBottom);
        mThumbDrawable.getPadding(mTempRect);
        finalint thumbPos = (int) (mThumbPosition + 0.5f);
        intthumbLeft = switchInnerLeft - mTempRect.left + thumbPos;
        intthumbRight = switchInnerLeft + thumbPos + mThumbWidth + mTempRect.right;        mThumbDrawable.setBounds(thumbLeft, switchTop, thumbRight, switchBottom);
        mThumbDrawable.draw(canvas);      
        if(mTextColors != null) {
            mTextPaint.setColor(mTextColors.getColorForState(getDrawableState(),
                    mTextColors.getDefaultColor()));
        }
        mTextPaint.drawableState = getDrawableState();        Layout switchText = getTargetCheckedState() ? mOnLayout : mOffLayout;        canvas.translate((thumbLeft + thumbRight) /2- switchText.getWidth() / 2,
                (switchInnerTop + switchInnerBottom) / 2- switchText.getHeight() / 2);
        switchText.draw(canvas);        canvas.restore();
   }    @Override
   publicint getCompoundPaddingRight() {
        intpadding = super.getCompoundPaddingRight() + mSwitchWidth;
        if(!TextUtils.isEmpty(getText())) {
            padding += mSwitchPadding;
        }
        returnpadding;
   }    privateint getThumbScrollRange() {
        if(mTrackDrawable == null) {
            return0;
        }
        mTrackDrawable.getPadding(mTempRect);
        returnmSwitchWidth - mThumbWidth - mTempRect.left - mTempRect.right;
   }    @Override
   protectedint[] onCreateDrawableState(intextraSpace) {
        finalint[] drawableState = super.onCreateDrawableState(extraSpace + 1);
        if(isChecked()) {
            mergeDrawableStates(drawableState, CHECKED_STATE_SET);
        }
        returndrawableState;
   }    @Override
   protectedvoid drawableStateChanged() {
        super.drawableStateChanged();        int[] myDrawableState = getDrawableState();
        if(mThumbDrawable != null) mThumbDrawable.setState(myDrawableState);
        if(mTrackDrawable != null) mTrackDrawable.setState(myDrawableState);        invalidate();
   }    @Override
   protectedboolean verifyDrawable(Drawable who) {
        returnsuper.verifyDrawable(who) || who == mThumbDrawable || who == mTrackDrawable;
   }}
直接拷贝4.0的源码是有问题的,很多新增的API是4.0之前没有的,需要修改一下。改动最大的部分有两个:
1. 注释掉了  jumpDrawablesToCurrentState() 这个函数,因为这是4.0的Drawable 里面新增的回调接口,这里不需要,就注释掉;
2. 4.0源码中的onPopulateAccessibilityEvent 这个函数是新增的回调函数,低级的SDK是没有的,怎么办。查看源码,发现这个函数只是在dispatchPopulateAccessibilityEvent调用了,将源码的Switch中的onPopulateAccessibilityEvent改成了poulateAccessibilityEvent还是在Switch的dispatchPopulateAccessibilityEvent调用就可以了。
还有就是需要增加Switch控件的属性,做过自定义控件属性的同学大概都知道。不多说,帖代码:

代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
<declare-styleable name="Switch">
        <!-- Drawable to use as the "thumb"that switches back and forth. -->
        <attr name="thumb"format="reference"/>
        <!-- Drawable to use as the "track"that the switchthumb slides within. -->
        <attr name="track"format="reference"/>
        <!-- Text to use when the switchis in the checked/"on"state. -->
        <attr name="textOn"format="string"/>
        <!-- Text to use when the switchis in the unchecked/"off"state. -->
        <attr name="textOff"format="string"/>
        <!-- Amount of padding on either side of text within the switchthumb. -->
        <attr name="thumbTextPadding"format="dimension"/>
        <!-- TextAppearance style fortext displayed on the switchthumb. -->
        <attr name="switchTextAppearance"format="reference"/>
        <!-- Minimum width forthe switchcomponent -->
        <attr name="switchMinWidth"format="dimension"/>
        <!-- Minimum space between the switchand caption text -->
        <attr name="switchPadding"format="dimension"/>
   </declare-styleable>


为了方便使用,直接定义了一个switch的style,设置了背景图片,拖拽的图片,显示文字等:
代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
11
12
<style name="Switch">
        <item name="track">@drawable/switch_track_holo_dark</item>
        <item name="thumb">@drawable/switch_inner_holo_dark</item>
        <!-- <item name="track">@drawable/switch_bg_default_mz</item>
        <item name="thumb">@drawable/switch_thumb_activated_mz</item> -->
        <item name="switchTextAppearance">@android:style/TextAppearance.Small</item>
        <item name="textOn">@string/switch_on</item>
        <item name="textOff">@string/switch_off</item>
        <item name="thumbTextPadding">12dip</item>
        <item name="switchMinWidth">96dip</item>
        <item name="switchPadding">16dip</item>
   </style>

0 0
原创粉丝点击