blob: 56f66510fe14419ce37882d3b6f08db5d381038a [file] [log] [blame]
Adam Powell12190b32010-11-28 19:07:53 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.widget;
18
Adam Powell12190b32010-11-28 19:07:53 -080019import android.content.Context;
20import android.content.res.ColorStateList;
21import android.content.res.Resources;
22import android.content.res.TypedArray;
23import android.graphics.Canvas;
24import android.graphics.Paint;
25import android.graphics.Rect;
26import android.graphics.Typeface;
27import android.graphics.drawable.Drawable;
28import android.text.Layout;
29import android.text.StaticLayout;
30import android.text.TextPaint;
31import android.text.TextUtils;
Daniel Sandler4c3308d2012-04-19 11:04:39 -040032import android.text.method.AllCapsTransformationMethod;
33import android.text.method.TransformationMethod2;
Adam Powell12190b32010-11-28 19:07:53 -080034import android.util.AttributeSet;
35import android.view.Gravity;
36import android.view.MotionEvent;
37import android.view.VelocityTracker;
38import android.view.ViewConfiguration;
Svetoslav Ganov63bce032011-07-23 19:52:17 -070039import android.view.accessibility.AccessibilityEvent;
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -080040import android.view.accessibility.AccessibilityNodeInfo;
Adam Powell12190b32010-11-28 19:07:53 -080041
Adam Powellbe0a4532010-11-29 17:47:48 -080042import com.android.internal.R;
43
Adam Powell12190b32010-11-28 19:07:53 -080044/**
45 * A Switch is a two-state toggle switch widget that can select between two
46 * options. The user may drag the "thumb" back and forth to choose the selected option,
Chet Haase150176d2011-08-26 09:54:06 -070047 * or simply tap to toggle as if it were a checkbox. The {@link #setText(CharSequence) text}
48 * property controls the text displayed in the label for the switch, whereas the
49 * {@link #setTextOff(CharSequence) off} and {@link #setTextOn(CharSequence) on} text
50 * controls the text on the thumb. Similarly, the
51 * {@link #setTextAppearance(android.content.Context, int) textAppearance} and the related
52 * setTypeface() methods control the typeface and style of label text, whereas the
53 * {@link #setSwitchTextAppearance(android.content.Context, int) switchTextAppearance} and
54 * the related seSwitchTypeface() methods control that of the thumb.
Adam Powell12190b32010-11-28 19:07:53 -080055 *
Scott Main4c359b72012-07-24 15:51:27 -070056 * <p>See the <a href="{@docRoot}guide/topics/ui/controls/togglebutton.html">Toggle Buttons</a>
57 * guide.</p>
58 *
59 * @attr ref android.R.styleable#Switch_textOn
60 * @attr ref android.R.styleable#Switch_textOff
61 * @attr ref android.R.styleable#Switch_switchMinWidth
62 * @attr ref android.R.styleable#Switch_switchPadding
63 * @attr ref android.R.styleable#Switch_switchTextAppearance
64 * @attr ref android.R.styleable#Switch_thumb
65 * @attr ref android.R.styleable#Switch_thumbTextPadding
66 * @attr ref android.R.styleable#Switch_track
Adam Powell12190b32010-11-28 19:07:53 -080067 */
68public class Switch extends CompoundButton {
69 private static final int TOUCH_MODE_IDLE = 0;
70 private static final int TOUCH_MODE_DOWN = 1;
71 private static final int TOUCH_MODE_DRAGGING = 2;
72
73 // Enum for the "typeface" XML parameter.
74 private static final int SANS = 1;
75 private static final int SERIF = 2;
76 private static final int MONOSPACE = 3;
77
78 private Drawable mThumbDrawable;
79 private Drawable mTrackDrawable;
80 private int mThumbTextPadding;
81 private int mSwitchMinWidth;
82 private int mSwitchPadding;
83 private CharSequence mTextOn;
84 private CharSequence mTextOff;
85
86 private int mTouchMode;
87 private int mTouchSlop;
88 private float mTouchX;
89 private float mTouchY;
90 private VelocityTracker mVelocityTracker = VelocityTracker.obtain();
91 private int mMinFlingVelocity;
92
93 private float mThumbPosition;
94 private int mSwitchWidth;
95 private int mSwitchHeight;
96 private int mThumbWidth; // Does not include padding
97
98 private int mSwitchLeft;
99 private int mSwitchTop;
100 private int mSwitchRight;
101 private int mSwitchBottom;
102
103 private TextPaint mTextPaint;
104 private ColorStateList mTextColors;
105 private Layout mOnLayout;
106 private Layout mOffLayout;
Daniel Sandler4c3308d2012-04-19 11:04:39 -0400107 private TransformationMethod2 mSwitchTransformationMethod;
Adam Powell12190b32010-11-28 19:07:53 -0800108
Adam Powellbe0a4532010-11-29 17:47:48 -0800109 @SuppressWarnings("hiding")
Adam Powell12190b32010-11-28 19:07:53 -0800110 private final Rect mTempRect = new Rect();
111
112 private static final int[] CHECKED_STATE_SET = {
113 R.attr.state_checked
114 };
115
116 /**
117 * Construct a new Switch with default styling.
118 *
119 * @param context The Context that will determine this widget's theming.
120 */
121 public Switch(Context context) {
122 this(context, null);
123 }
124
125 /**
126 * Construct a new Switch with default styling, overriding specific style
127 * attributes as requested.
128 *
129 * @param context The Context that will determine this widget's theming.
130 * @param attrs Specification of attributes that should deviate from default styling.
131 */
132 public Switch(Context context, AttributeSet attrs) {
133 this(context, attrs, com.android.internal.R.attr.switchStyle);
134 }
135
136 /**
137 * Construct a new Switch with a default style determined by the given theme attribute,
138 * overriding specific style attributes as requested.
139 *
140 * @param context The Context that will determine this widget's theming.
141 * @param attrs Specification of attributes that should deviate from the default styling.
142 * @param defStyle An attribute ID within the active theme containing a reference to the
143 * default style for this widget. e.g. android.R.attr.switchStyle.
144 */
145 public Switch(Context context, AttributeSet attrs, int defStyle) {
146 super(context, attrs, defStyle);
147
148 mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
149 Resources res = getResources();
150 mTextPaint.density = res.getDisplayMetrics().density;
151 mTextPaint.setCompatibilityScaling(res.getCompatibilityInfo().applicationScale);
152
153 TypedArray a = context.obtainStyledAttributes(attrs,
154 com.android.internal.R.styleable.Switch, defStyle, 0);
155
Chet Haase150176d2011-08-26 09:54:06 -0700156 mThumbDrawable = a.getDrawable(com.android.internal.R.styleable.Switch_thumb);
157 mTrackDrawable = a.getDrawable(com.android.internal.R.styleable.Switch_track);
Adam Powell12190b32010-11-28 19:07:53 -0800158 mTextOn = a.getText(com.android.internal.R.styleable.Switch_textOn);
159 mTextOff = a.getText(com.android.internal.R.styleable.Switch_textOff);
160 mThumbTextPadding = a.getDimensionPixelSize(
161 com.android.internal.R.styleable.Switch_thumbTextPadding, 0);
162 mSwitchMinWidth = a.getDimensionPixelSize(
163 com.android.internal.R.styleable.Switch_switchMinWidth, 0);
164 mSwitchPadding = a.getDimensionPixelSize(
165 com.android.internal.R.styleable.Switch_switchPadding, 0);
166
167 int appearance = a.getResourceId(
168 com.android.internal.R.styleable.Switch_switchTextAppearance, 0);
169 if (appearance != 0) {
Chet Haase150176d2011-08-26 09:54:06 -0700170 setSwitchTextAppearance(context, appearance);
Adam Powell12190b32010-11-28 19:07:53 -0800171 }
172 a.recycle();
173
174 ViewConfiguration config = ViewConfiguration.get(context);
175 mTouchSlop = config.getScaledTouchSlop();
176 mMinFlingVelocity = config.getScaledMinimumFlingVelocity();
177
178 // Refresh display with current params
Gilles Debunnee724ee42011-08-31 11:20:27 -0700179 refreshDrawableState();
Adam Powell12190b32010-11-28 19:07:53 -0800180 setChecked(isChecked());
181 }
182
183 /**
184 * Sets the switch text color, size, style, hint color, and highlight color
185 * from the specified TextAppearance resource.
Adam Powell6c86e1b2012-03-08 15:11:46 -0800186 *
187 * @attr ref android.R.styleable#Switch_switchTextAppearance
Adam Powell12190b32010-11-28 19:07:53 -0800188 */
Chet Haase150176d2011-08-26 09:54:06 -0700189 public void setSwitchTextAppearance(Context context, int resid) {
Adam Powell12190b32010-11-28 19:07:53 -0800190 TypedArray appearance =
Chet Haase150176d2011-08-26 09:54:06 -0700191 context.obtainStyledAttributes(resid,
Adam Powell12190b32010-11-28 19:07:53 -0800192 com.android.internal.R.styleable.TextAppearance);
193
194 ColorStateList colors;
195 int ts;
196
197 colors = appearance.getColorStateList(com.android.internal.R.styleable.
198 TextAppearance_textColor);
199 if (colors != null) {
200 mTextColors = colors;
Chet Haase150176d2011-08-26 09:54:06 -0700201 } else {
202 // If no color set in TextAppearance, default to the view's textColor
203 mTextColors = getTextColors();
Adam Powell12190b32010-11-28 19:07:53 -0800204 }
205
206 ts = appearance.getDimensionPixelSize(com.android.internal.R.styleable.
207 TextAppearance_textSize, 0);
208 if (ts != 0) {
209 if (ts != mTextPaint.getTextSize()) {
210 mTextPaint.setTextSize(ts);
211 requestLayout();
212 }
213 }
214
215 int typefaceIndex, styleIndex;
216
217 typefaceIndex = appearance.getInt(com.android.internal.R.styleable.
218 TextAppearance_typeface, -1);
219 styleIndex = appearance.getInt(com.android.internal.R.styleable.
220 TextAppearance_textStyle, -1);
221
222 setSwitchTypefaceByIndex(typefaceIndex, styleIndex);
223
Daniel Sandler4c3308d2012-04-19 11:04:39 -0400224 boolean allCaps = appearance.getBoolean(com.android.internal.R.styleable.
225 TextAppearance_textAllCaps, false);
226 if (allCaps) {
227 mSwitchTransformationMethod = new AllCapsTransformationMethod(getContext());
228 mSwitchTransformationMethod.setLengthChangesAllowed(true);
229 } else {
230 mSwitchTransformationMethod = null;
231 }
232
Adam Powell12190b32010-11-28 19:07:53 -0800233 appearance.recycle();
234 }
235
236 private void setSwitchTypefaceByIndex(int typefaceIndex, int styleIndex) {
237 Typeface tf = null;
238 switch (typefaceIndex) {
239 case SANS:
240 tf = Typeface.SANS_SERIF;
241 break;
242
243 case SERIF:
244 tf = Typeface.SERIF;
245 break;
246
247 case MONOSPACE:
248 tf = Typeface.MONOSPACE;
249 break;
250 }
251
252 setSwitchTypeface(tf, styleIndex);
253 }
254
255 /**
256 * Sets the typeface and style in which the text should be displayed on the
257 * switch, and turns on the fake bold and italic bits in the Paint if the
258 * Typeface that you provided does not have all the bits in the
259 * style that you specified.
260 */
261 public void setSwitchTypeface(Typeface tf, int style) {
262 if (style > 0) {
263 if (tf == null) {
264 tf = Typeface.defaultFromStyle(style);
265 } else {
266 tf = Typeface.create(tf, style);
267 }
268
269 setSwitchTypeface(tf);
270 // now compute what (if any) algorithmic styling is needed
271 int typefaceStyle = tf != null ? tf.getStyle() : 0;
272 int need = style & ~typefaceStyle;
273 mTextPaint.setFakeBoldText((need & Typeface.BOLD) != 0);
274 mTextPaint.setTextSkewX((need & Typeface.ITALIC) != 0 ? -0.25f : 0);
275 } else {
Victoria Leaseaa0980a2012-06-11 14:46:04 -0700276 mTextPaint.setFakeBoldText(false);
Adam Powell12190b32010-11-28 19:07:53 -0800277 mTextPaint.setTextSkewX(0);
278 setSwitchTypeface(tf);
279 }
280 }
281
282 /**
Chet Haase150176d2011-08-26 09:54:06 -0700283 * Sets the typeface in which the text should be displayed on the switch.
Adam Powell12190b32010-11-28 19:07:53 -0800284 * Note that not all Typeface families actually have bold and italic
285 * variants, so you may need to use
286 * {@link #setSwitchTypeface(Typeface, int)} to get the appearance
287 * that you actually want.
288 *
289 * @attr ref android.R.styleable#TextView_typeface
290 * @attr ref android.R.styleable#TextView_textStyle
291 */
292 public void setSwitchTypeface(Typeface tf) {
293 if (mTextPaint.getTypeface() != tf) {
294 mTextPaint.setTypeface(tf);
295
296 requestLayout();
297 invalidate();
298 }
299 }
300
301 /**
Adam Powell6c86e1b2012-03-08 15:11:46 -0800302 * Set the amount of horizontal padding between the switch and the associated text.
303 *
304 * @param pixels Amount of padding in pixels
305 *
306 * @attr ref android.R.styleable#Switch_switchPadding
307 */
308 public void setSwitchPadding(int pixels) {
309 mSwitchPadding = pixels;
310 requestLayout();
311 }
312
313 /**
314 * Get the amount of horizontal padding between the switch and the associated text.
315 *
316 * @return Amount of padding in pixels
317 *
318 * @attr ref android.R.styleable#Switch_switchPadding
319 */
320 public int getSwitchPadding() {
321 return mSwitchPadding;
322 }
323
324 /**
325 * Set the minimum width of the switch in pixels. The switch's width will be the maximum
326 * of this value and its measured width as determined by the switch drawables and text used.
327 *
328 * @param pixels Minimum width of the switch in pixels
329 *
330 * @attr ref android.R.styleable#Switch_switchMinWidth
331 */
332 public void setSwitchMinWidth(int pixels) {
333 mSwitchMinWidth = pixels;
334 requestLayout();
335 }
336
337 /**
338 * Get the minimum width of the switch in pixels. The switch's width will be the maximum
339 * of this value and its measured width as determined by the switch drawables and text used.
340 *
341 * @return Minimum width of the switch in pixels
342 *
343 * @attr ref android.R.styleable#Switch_switchMinWidth
344 */
345 public int getSwitchMinWidth() {
346 return mSwitchMinWidth;
347 }
348
349 /**
350 * Set the horizontal padding around the text drawn on the switch itself.
351 *
352 * @param pixels Horizontal padding for switch thumb text in pixels
353 *
354 * @attr ref android.R.styleable#Switch_thumbTextPadding
355 */
356 public void setThumbTextPadding(int pixels) {
357 mThumbTextPadding = pixels;
358 requestLayout();
359 }
360
361 /**
362 * Get the horizontal padding around the text drawn on the switch itself.
363 *
364 * @return Horizontal padding for switch thumb text in pixels
365 *
366 * @attr ref android.R.styleable#Switch_thumbTextPadding
367 */
368 public int getThumbTextPadding() {
369 return mThumbTextPadding;
370 }
371
372 /**
373 * Set the drawable used for the track that the switch slides within.
374 *
375 * @param track Track drawable
376 *
377 * @attr ref android.R.styleable#Switch_track
378 */
379 public void setTrackDrawable(Drawable track) {
380 mTrackDrawable = track;
381 requestLayout();
382 }
383
384 /**
Adam Powelld9c7be62012-03-08 19:43:43 -0800385 * Set the drawable used for the track that the switch slides within.
386 *
Adam Powelldca510e2012-03-08 20:06:39 -0800387 * @param resId Resource ID of a track drawable
Adam Powelld9c7be62012-03-08 19:43:43 -0800388 *
389 * @attr ref android.R.styleable#Switch_track
390 */
391 public void setTrackResource(int resId) {
392 setTrackDrawable(getContext().getResources().getDrawable(resId));
393 }
394
395 /**
Adam Powell6c86e1b2012-03-08 15:11:46 -0800396 * Get the drawable used for the track that the switch slides within.
397 *
398 * @return Track drawable
399 *
400 * @attr ref android.R.styleable#Switch_track
401 */
402 public Drawable getTrackDrawable() {
403 return mTrackDrawable;
404 }
405
406 /**
407 * Set the drawable used for the switch "thumb" - the piece that the user
408 * can physically touch and drag along the track.
409 *
410 * @param thumb Thumb drawable
411 *
412 * @attr ref android.R.styleable#Switch_thumb
413 */
414 public void setThumbDrawable(Drawable thumb) {
415 mThumbDrawable = thumb;
416 requestLayout();
417 }
418
419 /**
Adam Powelld9c7be62012-03-08 19:43:43 -0800420 * Set the drawable used for the switch "thumb" - the piece that the user
421 * can physically touch and drag along the track.
422 *
Adam Powelldca510e2012-03-08 20:06:39 -0800423 * @param resId Resource ID of a thumb drawable
Adam Powelld9c7be62012-03-08 19:43:43 -0800424 *
425 * @attr ref android.R.styleable#Switch_thumb
426 */
427 public void setThumbResource(int resId) {
428 setThumbDrawable(getContext().getResources().getDrawable(resId));
429 }
430
431 /**
Adam Powell6c86e1b2012-03-08 15:11:46 -0800432 * Get the drawable used for the switch "thumb" - the piece that the user
433 * can physically touch and drag along the track.
434 *
435 * @return Thumb drawable
436 *
437 * @attr ref android.R.styleable#Switch_thumb
438 */
439 public Drawable getThumbDrawable() {
440 return mThumbDrawable;
441 }
442
443 /**
Chet Haase150176d2011-08-26 09:54:06 -0700444 * Returns the text displayed when the button is in the checked state.
Adam Powell6c86e1b2012-03-08 15:11:46 -0800445 *
446 * @attr ref android.R.styleable#Switch_textOn
Adam Powell12190b32010-11-28 19:07:53 -0800447 */
448 public CharSequence getTextOn() {
449 return mTextOn;
450 }
451
452 /**
Chet Haase150176d2011-08-26 09:54:06 -0700453 * Sets the text displayed when the button is in the checked state.
Adam Powell6c86e1b2012-03-08 15:11:46 -0800454 *
455 * @attr ref android.R.styleable#Switch_textOn
Adam Powell12190b32010-11-28 19:07:53 -0800456 */
457 public void setTextOn(CharSequence textOn) {
458 mTextOn = textOn;
459 requestLayout();
460 }
461
462 /**
Chet Haase150176d2011-08-26 09:54:06 -0700463 * Returns the text displayed when the button is not in the checked state.
Adam Powell6c86e1b2012-03-08 15:11:46 -0800464 *
465 * @attr ref android.R.styleable#Switch_textOff
Adam Powell12190b32010-11-28 19:07:53 -0800466 */
467 public CharSequence getTextOff() {
468 return mTextOff;
469 }
470
471 /**
Chet Haase150176d2011-08-26 09:54:06 -0700472 * Sets the text displayed when the button is not in the checked state.
Adam Powell6c86e1b2012-03-08 15:11:46 -0800473 *
474 * @attr ref android.R.styleable#Switch_textOff
Adam Powell12190b32010-11-28 19:07:53 -0800475 */
476 public void setTextOff(CharSequence textOff) {
477 mTextOff = textOff;
478 requestLayout();
479 }
480
481 @Override
482 public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
483 final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
484 final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
485 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
486 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
487
488
489 if (mOnLayout == null) {
490 mOnLayout = makeLayout(mTextOn);
491 }
492 if (mOffLayout == null) {
493 mOffLayout = makeLayout(mTextOff);
494 }
495
496 mTrackDrawable.getPadding(mTempRect);
497 final int maxTextWidth = Math.max(mOnLayout.getWidth(), mOffLayout.getWidth());
498 final int switchWidth = Math.max(mSwitchMinWidth,
499 maxTextWidth * 2 + mThumbTextPadding * 4 + mTempRect.left + mTempRect.right);
500 final int switchHeight = mTrackDrawable.getIntrinsicHeight();
501
502 mThumbWidth = maxTextWidth + mThumbTextPadding * 2;
503
504 switch (widthMode) {
505 case MeasureSpec.AT_MOST:
506 widthSize = Math.min(widthSize, switchWidth);
507 break;
508
509 case MeasureSpec.UNSPECIFIED:
510 widthSize = switchWidth;
511 break;
512
513 case MeasureSpec.EXACTLY:
514 // Just use what we were given
515 break;
516 }
517
518 switch (heightMode) {
519 case MeasureSpec.AT_MOST:
520 heightSize = Math.min(heightSize, switchHeight);
521 break;
522
523 case MeasureSpec.UNSPECIFIED:
524 heightSize = switchHeight;
525 break;
526
527 case MeasureSpec.EXACTLY:
528 // Just use what we were given
529 break;
530 }
531
532 mSwitchWidth = switchWidth;
533 mSwitchHeight = switchHeight;
534
535 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
Adam Powell12190b32010-11-28 19:07:53 -0800536 final int measuredHeight = getMeasuredHeight();
537 if (measuredHeight < switchHeight) {
Dianne Hackborn189ee182010-12-02 21:48:53 -0800538 setMeasuredDimension(getMeasuredWidthAndState(), switchHeight);
Adam Powell12190b32010-11-28 19:07:53 -0800539 }
540 }
541
Svetoslav Ganov63bce032011-07-23 19:52:17 -0700542 @Override
543 public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
544 super.onPopulateAccessibilityEvent(event);
Svetoslav Ganov55249c82012-03-09 10:09:03 -0800545 CharSequence text = isChecked() ? mOnLayout.getText() : mOffLayout.getText();
546 if (!TextUtils.isEmpty(text)) {
Svetoslav Ganov76502592011-07-29 10:44:59 -0700547 event.getText().add(text);
548 }
Svetoslav Ganov63bce032011-07-23 19:52:17 -0700549 }
550
Adam Powell12190b32010-11-28 19:07:53 -0800551 private Layout makeLayout(CharSequence text) {
Daniel Sandler4c3308d2012-04-19 11:04:39 -0400552 final CharSequence transformed = (mSwitchTransformationMethod != null)
553 ? mSwitchTransformationMethod.getTransformation(text, this)
554 : text;
555
556 return new StaticLayout(transformed, mTextPaint,
557 (int) Math.ceil(Layout.getDesiredWidth(transformed, mTextPaint)),
Adam Powell12190b32010-11-28 19:07:53 -0800558 Layout.Alignment.ALIGN_NORMAL, 1.f, 0, true);
559 }
560
561 /**
562 * @return true if (x, y) is within the target area of the switch thumb
563 */
564 private boolean hitThumb(float x, float y) {
565 mThumbDrawable.getPadding(mTempRect);
566 final int thumbTop = mSwitchTop - mTouchSlop;
567 final int thumbLeft = mSwitchLeft + (int) (mThumbPosition + 0.5f) - mTouchSlop;
568 final int thumbRight = thumbLeft + mThumbWidth +
569 mTempRect.left + mTempRect.right + mTouchSlop;
570 final int thumbBottom = mSwitchBottom + mTouchSlop;
571 return x > thumbLeft && x < thumbRight && y > thumbTop && y < thumbBottom;
572 }
573
574 @Override
575 public boolean onTouchEvent(MotionEvent ev) {
576 mVelocityTracker.addMovement(ev);
577 final int action = ev.getActionMasked();
578 switch (action) {
579 case MotionEvent.ACTION_DOWN: {
580 final float x = ev.getX();
581 final float y = ev.getY();
Gilles Debunnec2ab0d62011-06-13 12:52:48 -0700582 if (isEnabled() && hitThumb(x, y)) {
Adam Powell12190b32010-11-28 19:07:53 -0800583 mTouchMode = TOUCH_MODE_DOWN;
584 mTouchX = x;
585 mTouchY = y;
586 }
587 break;
588 }
589
590 case MotionEvent.ACTION_MOVE: {
591 switch (mTouchMode) {
592 case TOUCH_MODE_IDLE:
593 // Didn't target the thumb, treat normally.
594 break;
595
596 case TOUCH_MODE_DOWN: {
597 final float x = ev.getX();
598 final float y = ev.getY();
599 if (Math.abs(x - mTouchX) > mTouchSlop ||
600 Math.abs(y - mTouchY) > mTouchSlop) {
601 mTouchMode = TOUCH_MODE_DRAGGING;
602 getParent().requestDisallowInterceptTouchEvent(true);
603 mTouchX = x;
604 mTouchY = y;
605 return true;
606 }
607 break;
608 }
609
610 case TOUCH_MODE_DRAGGING: {
611 final float x = ev.getX();
612 final float dx = x - mTouchX;
613 float newPos = Math.max(0,
614 Math.min(mThumbPosition + dx, getThumbScrollRange()));
615 if (newPos != mThumbPosition) {
616 mThumbPosition = newPos;
617 mTouchX = x;
618 invalidate();
619 }
620 return true;
621 }
622 }
623 break;
624 }
625
626 case MotionEvent.ACTION_UP:
627 case MotionEvent.ACTION_CANCEL: {
628 if (mTouchMode == TOUCH_MODE_DRAGGING) {
629 stopDrag(ev);
630 return true;
631 }
632 mTouchMode = TOUCH_MODE_IDLE;
633 mVelocityTracker.clear();
634 break;
635 }
636 }
637
638 return super.onTouchEvent(ev);
639 }
640
641 private void cancelSuperTouch(MotionEvent ev) {
642 MotionEvent cancel = MotionEvent.obtain(ev);
643 cancel.setAction(MotionEvent.ACTION_CANCEL);
644 super.onTouchEvent(cancel);
645 cancel.recycle();
646 }
647
648 /**
649 * Called from onTouchEvent to end a drag operation.
650 *
651 * @param ev Event that triggered the end of drag mode - ACTION_UP or ACTION_CANCEL
652 */
653 private void stopDrag(MotionEvent ev) {
654 mTouchMode = TOUCH_MODE_IDLE;
Gilles Debunnec2ab0d62011-06-13 12:52:48 -0700655 // Up and not canceled, also checks the switch has not been disabled during the drag
656 boolean commitChange = ev.getAction() == MotionEvent.ACTION_UP && isEnabled();
Adam Powell12190b32010-11-28 19:07:53 -0800657
658 cancelSuperTouch(ev);
659
660 if (commitChange) {
661 boolean newState;
662 mVelocityTracker.computeCurrentVelocity(1000);
663 float xvel = mVelocityTracker.getXVelocity();
664 if (Math.abs(xvel) > mMinFlingVelocity) {
Adam Powell01d11ed2011-08-09 16:32:12 -0700665 newState = xvel > 0;
Adam Powell12190b32010-11-28 19:07:53 -0800666 } else {
667 newState = getTargetCheckedState();
668 }
669 animateThumbToCheckedState(newState);
670 } else {
671 animateThumbToCheckedState(isChecked());
672 }
673 }
674
675 private void animateThumbToCheckedState(boolean newCheckedState) {
Adam Powell12190b32010-11-28 19:07:53 -0800676 // TODO animate!
Joe Onoratoc3eabb92011-01-07 15:58:44 -0800677 //float targetPos = newCheckedState ? 0 : getThumbScrollRange();
678 //mThumbPosition = targetPos;
Adam Powell12190b32010-11-28 19:07:53 -0800679 setChecked(newCheckedState);
680 }
681
682 private boolean getTargetCheckedState() {
Adam Powellec1d6032011-08-07 18:03:39 -0700683 return mThumbPosition >= getThumbScrollRange() / 2;
Adam Powell12190b32010-11-28 19:07:53 -0800684 }
685
686 @Override
687 public void setChecked(boolean checked) {
688 super.setChecked(checked);
Adam Powellec1d6032011-08-07 18:03:39 -0700689 mThumbPosition = checked ? getThumbScrollRange() : 0;
Joe Onoratoc3eabb92011-01-07 15:58:44 -0800690 invalidate();
Adam Powell12190b32010-11-28 19:07:53 -0800691 }
692
693 @Override
694 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
695 super.onLayout(changed, left, top, right, bottom);
696
Adam Powellec1d6032011-08-07 18:03:39 -0700697 mThumbPosition = isChecked() ? getThumbScrollRange() : 0;
Joe Onoratoc3eabb92011-01-07 15:58:44 -0800698
Adam Powell12190b32010-11-28 19:07:53 -0800699 int switchRight = getWidth() - getPaddingRight();
700 int switchLeft = switchRight - mSwitchWidth;
701 int switchTop = 0;
702 int switchBottom = 0;
703 switch (getGravity() & Gravity.VERTICAL_GRAVITY_MASK) {
704 default:
705 case Gravity.TOP:
706 switchTop = getPaddingTop();
707 switchBottom = switchTop + mSwitchHeight;
708 break;
709
710 case Gravity.CENTER_VERTICAL:
711 switchTop = (getPaddingTop() + getHeight() - getPaddingBottom()) / 2 -
712 mSwitchHeight / 2;
713 switchBottom = switchTop + mSwitchHeight;
714 break;
715
716 case Gravity.BOTTOM:
717 switchBottom = getHeight() - getPaddingBottom();
718 switchTop = switchBottom - mSwitchHeight;
719 break;
720 }
721
722 mSwitchLeft = switchLeft;
723 mSwitchTop = switchTop;
724 mSwitchBottom = switchBottom;
725 mSwitchRight = switchRight;
726 }
727
728 @Override
729 protected void onDraw(Canvas canvas) {
730 super.onDraw(canvas);
731
732 // Draw the switch
733 int switchLeft = mSwitchLeft;
734 int switchTop = mSwitchTop;
735 int switchRight = mSwitchRight;
736 int switchBottom = mSwitchBottom;
737
738 mTrackDrawable.setBounds(switchLeft, switchTop, switchRight, switchBottom);
739 mTrackDrawable.draw(canvas);
740
741 canvas.save();
742
743 mTrackDrawable.getPadding(mTempRect);
744 int switchInnerLeft = switchLeft + mTempRect.left;
745 int switchInnerTop = switchTop + mTempRect.top;
746 int switchInnerRight = switchRight - mTempRect.right;
747 int switchInnerBottom = switchBottom - mTempRect.bottom;
748 canvas.clipRect(switchInnerLeft, switchTop, switchInnerRight, switchBottom);
749
750 mThumbDrawable.getPadding(mTempRect);
751 final int thumbPos = (int) (mThumbPosition + 0.5f);
752 int thumbLeft = switchInnerLeft - mTempRect.left + thumbPos;
753 int thumbRight = switchInnerLeft + thumbPos + mThumbWidth + mTempRect.right;
754
755 mThumbDrawable.setBounds(thumbLeft, switchTop, thumbRight, switchBottom);
756 mThumbDrawable.draw(canvas);
757
Chet Haase150176d2011-08-26 09:54:06 -0700758 // mTextColors should not be null, but just in case
759 if (mTextColors != null) {
760 mTextPaint.setColor(mTextColors.getColorForState(getDrawableState(),
761 mTextColors.getDefaultColor()));
762 }
Adam Powell12190b32010-11-28 19:07:53 -0800763 mTextPaint.drawableState = getDrawableState();
764
765 Layout switchText = getTargetCheckedState() ? mOnLayout : mOffLayout;
766
767 canvas.translate((thumbLeft + thumbRight) / 2 - switchText.getWidth() / 2,
768 (switchInnerTop + switchInnerBottom) / 2 - switchText.getHeight() / 2);
769 switchText.draw(canvas);
770
771 canvas.restore();
772 }
773
774 @Override
775 public int getCompoundPaddingRight() {
776 int padding = super.getCompoundPaddingRight() + mSwitchWidth;
777 if (!TextUtils.isEmpty(getText())) {
778 padding += mSwitchPadding;
779 }
780 return padding;
781 }
782
783 private int getThumbScrollRange() {
784 if (mTrackDrawable == null) {
785 return 0;
786 }
787 mTrackDrawable.getPadding(mTempRect);
788 return mSwitchWidth - mThumbWidth - mTempRect.left - mTempRect.right;
789 }
790
791 @Override
792 protected int[] onCreateDrawableState(int extraSpace) {
793 final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
794 if (isChecked()) {
795 mergeDrawableStates(drawableState, CHECKED_STATE_SET);
796 }
797 return drawableState;
798 }
799
800 @Override
801 protected void drawableStateChanged() {
802 super.drawableStateChanged();
803
804 int[] myDrawableState = getDrawableState();
805
806 // Set the state of the Drawable
Gilles Debunnee724ee42011-08-31 11:20:27 -0700807 // Drawable may be null when checked state is set from XML, from super constructor
808 if (mThumbDrawable != null) mThumbDrawable.setState(myDrawableState);
809 if (mTrackDrawable != null) mTrackDrawable.setState(myDrawableState);
Adam Powell12190b32010-11-28 19:07:53 -0800810
811 invalidate();
812 }
813
814 @Override
815 protected boolean verifyDrawable(Drawable who) {
816 return super.verifyDrawable(who) || who == mThumbDrawable || who == mTrackDrawable;
817 }
818
819 @Override
820 public void jumpDrawablesToCurrentState() {
821 super.jumpDrawablesToCurrentState();
822 mThumbDrawable.jumpToCurrentState();
823 mTrackDrawable.jumpToCurrentState();
824 }
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -0800825
826 @Override
827 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
828 super.onInitializeAccessibilityEvent(event);
829 event.setClassName(Switch.class.getName());
830 }
831
832 @Override
833 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
834 super.onInitializeAccessibilityNodeInfo(info);
835 info.setClassName(Switch.class.getName());
Svetoslav Ganov78bcc152012-04-12 17:17:19 -0700836 CharSequence switchText = isChecked() ? mTextOn : mTextOff;
837 if (!TextUtils.isEmpty(switchText)) {
838 CharSequence oldText = info.getText();
839 if (TextUtils.isEmpty(oldText)) {
840 info.setText(switchText);
841 } else {
842 StringBuilder newText = new StringBuilder();
843 newText.append(oldText).append(' ').append(switchText);
844 info.setText(newText);
845 }
846 }
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -0800847 }
Adam Powell12190b32010-11-28 19:07:53 -0800848}