blob: 13d6b42361e6f8d1af7cd50193618fa4ed8458cd [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
Alan Viverettecc2688d2013-09-17 17:00:12 -070019import android.animation.ObjectAnimator;
Adam Powell12190b32010-11-28 19:07:53 -080020import android.content.Context;
21import android.content.res.ColorStateList;
22import android.content.res.Resources;
23import android.content.res.TypedArray;
24import android.graphics.Canvas;
Alan Viverette661e6362014-05-12 10:55:37 -070025import android.graphics.Insets;
Adam Powell12190b32010-11-28 19:07:53 -080026import android.graphics.Paint;
27import android.graphics.Rect;
28import android.graphics.Typeface;
Alan Viverette661e6362014-05-12 10:55:37 -070029import android.graphics.Region.Op;
Adam Powell12190b32010-11-28 19:07:53 -080030import android.graphics.drawable.Drawable;
31import android.text.Layout;
32import android.text.StaticLayout;
33import android.text.TextPaint;
34import android.text.TextUtils;
Daniel Sandler4c3308d2012-04-19 11:04:39 -040035import android.text.method.AllCapsTransformationMethod;
36import android.text.method.TransformationMethod2;
Adam Powell12190b32010-11-28 19:07:53 -080037import android.util.AttributeSet;
Alan Viverettecc2688d2013-09-17 17:00:12 -070038import android.util.FloatProperty;
39import android.util.MathUtils;
Adam Powell12190b32010-11-28 19:07:53 -080040import android.view.Gravity;
41import android.view.MotionEvent;
Alan Viveretted4e77902014-10-27 17:50:51 -070042import android.view.SoundEffectConstants;
Adam Powell12190b32010-11-28 19:07:53 -080043import android.view.VelocityTracker;
44import android.view.ViewConfiguration;
Svetoslav Ganov63bce032011-07-23 19:52:17 -070045import android.view.accessibility.AccessibilityEvent;
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -080046import android.view.accessibility.AccessibilityNodeInfo;
Adam Powell12190b32010-11-28 19:07:53 -080047
Adam Powellbe0a4532010-11-29 17:47:48 -080048import com.android.internal.R;
49
Adam Powell12190b32010-11-28 19:07:53 -080050/**
51 * A Switch is a two-state toggle switch widget that can select between two
52 * options. The user may drag the "thumb" back and forth to choose the selected option,
Chet Haase150176d2011-08-26 09:54:06 -070053 * or simply tap to toggle as if it were a checkbox. The {@link #setText(CharSequence) text}
54 * property controls the text displayed in the label for the switch, whereas the
55 * {@link #setTextOff(CharSequence) off} and {@link #setTextOn(CharSequence) on} text
56 * controls the text on the thumb. Similarly, the
57 * {@link #setTextAppearance(android.content.Context, int) textAppearance} and the related
58 * setTypeface() methods control the typeface and style of label text, whereas the
59 * {@link #setSwitchTextAppearance(android.content.Context, int) switchTextAppearance} and
60 * the related seSwitchTypeface() methods control that of the thumb.
Adam Powell12190b32010-11-28 19:07:53 -080061 *
Scott Main4c359b72012-07-24 15:51:27 -070062 * <p>See the <a href="{@docRoot}guide/topics/ui/controls/togglebutton.html">Toggle Buttons</a>
63 * guide.</p>
64 *
65 * @attr ref android.R.styleable#Switch_textOn
66 * @attr ref android.R.styleable#Switch_textOff
67 * @attr ref android.R.styleable#Switch_switchMinWidth
68 * @attr ref android.R.styleable#Switch_switchPadding
69 * @attr ref android.R.styleable#Switch_switchTextAppearance
70 * @attr ref android.R.styleable#Switch_thumb
71 * @attr ref android.R.styleable#Switch_thumbTextPadding
72 * @attr ref android.R.styleable#Switch_track
Adam Powell12190b32010-11-28 19:07:53 -080073 */
74public class Switch extends CompoundButton {
Alan Viverettecc2688d2013-09-17 17:00:12 -070075 private static final int THUMB_ANIMATION_DURATION = 250;
76
Adam Powell12190b32010-11-28 19:07:53 -080077 private static final int TOUCH_MODE_IDLE = 0;
78 private static final int TOUCH_MODE_DOWN = 1;
79 private static final int TOUCH_MODE_DRAGGING = 2;
80
81 // Enum for the "typeface" XML parameter.
82 private static final int SANS = 1;
83 private static final int SERIF = 2;
84 private static final int MONOSPACE = 3;
85
86 private Drawable mThumbDrawable;
87 private Drawable mTrackDrawable;
88 private int mThumbTextPadding;
89 private int mSwitchMinWidth;
90 private int mSwitchPadding;
Alan Viverette661e6362014-05-12 10:55:37 -070091 private boolean mSplitTrack;
Adam Powell12190b32010-11-28 19:07:53 -080092 private CharSequence mTextOn;
93 private CharSequence mTextOff;
Alan Viverette2a37cf8d2014-06-19 17:09:10 -070094 private boolean mShowText;
Adam Powell12190b32010-11-28 19:07:53 -080095
96 private int mTouchMode;
97 private int mTouchSlop;
98 private float mTouchX;
99 private float mTouchY;
100 private VelocityTracker mVelocityTracker = VelocityTracker.obtain();
101 private int mMinFlingVelocity;
102
103 private float mThumbPosition;
Alan Viverette8bb39902014-07-29 17:22:30 -0700104
Alan Viverette0c0dde72014-07-30 13:29:39 -0700105 /**
106 * Width required to draw the switch track and thumb. Includes padding and
107 * optical bounds for both the track and thumb.
108 */
109 private int mSwitchWidth;
110
111 /**
112 * Height required to draw the switch track and thumb. Includes padding and
113 * optical bounds for both the track and thumb.
114 */
115 private int mSwitchHeight;
116
117 /**
118 * Width of the thumb's content region. Does not include padding or
119 * optical bounds.
120 */
121 private int mThumbWidth;
122
123 /** Left bound for drawing the switch track and thumb. */
Adam Powell12190b32010-11-28 19:07:53 -0800124 private int mSwitchLeft;
Alan Viverette0c0dde72014-07-30 13:29:39 -0700125
126 /** Top bound for drawing the switch track and thumb. */
Adam Powell12190b32010-11-28 19:07:53 -0800127 private int mSwitchTop;
Alan Viverette0c0dde72014-07-30 13:29:39 -0700128
129 /** Right bound for drawing the switch track and thumb. */
Adam Powell12190b32010-11-28 19:07:53 -0800130 private int mSwitchRight;
Alan Viverette0c0dde72014-07-30 13:29:39 -0700131
132 /** Bottom bound for drawing the switch track and thumb. */
Adam Powell12190b32010-11-28 19:07:53 -0800133 private int mSwitchBottom;
134
135 private TextPaint mTextPaint;
136 private ColorStateList mTextColors;
137 private Layout mOnLayout;
138 private Layout mOffLayout;
Daniel Sandler4c3308d2012-04-19 11:04:39 -0400139 private TransformationMethod2 mSwitchTransformationMethod;
Alan Viverettecc2688d2013-09-17 17:00:12 -0700140 private ObjectAnimator mPositionAnimator;
Adam Powell12190b32010-11-28 19:07:53 -0800141
Adam Powellbe0a4532010-11-29 17:47:48 -0800142 @SuppressWarnings("hiding")
Adam Powell12190b32010-11-28 19:07:53 -0800143 private final Rect mTempRect = new Rect();
144
145 private static final int[] CHECKED_STATE_SET = {
146 R.attr.state_checked
147 };
148
149 /**
150 * Construct a new Switch with default styling.
151 *
152 * @param context The Context that will determine this widget's theming.
153 */
154 public Switch(Context context) {
155 this(context, null);
156 }
157
158 /**
159 * Construct a new Switch with default styling, overriding specific style
160 * attributes as requested.
161 *
162 * @param context The Context that will determine this widget's theming.
163 * @param attrs Specification of attributes that should deviate from default styling.
164 */
165 public Switch(Context context, AttributeSet attrs) {
166 this(context, attrs, com.android.internal.R.attr.switchStyle);
167 }
168
169 /**
170 * Construct a new Switch with a default style determined by the given theme attribute,
171 * overriding specific style attributes as requested.
172 *
173 * @param context The Context that will determine this widget's theming.
174 * @param attrs Specification of attributes that should deviate from the default styling.
Alan Viverette617feb92013-09-09 18:09:13 -0700175 * @param defStyleAttr An attribute in the current theme that contains a
176 * reference to a style resource that supplies default values for
177 * the view. Can be 0 to not look for defaults.
Adam Powell12190b32010-11-28 19:07:53 -0800178 */
Alan Viverette617feb92013-09-09 18:09:13 -0700179 public Switch(Context context, AttributeSet attrs, int defStyleAttr) {
180 this(context, attrs, defStyleAttr, 0);
181 }
182
183
184 /**
185 * Construct a new Switch with a default style determined by the given theme
186 * attribute or style resource, overriding specific style attributes as
187 * requested.
188 *
189 * @param context The Context that will determine this widget's theming.
190 * @param attrs Specification of attributes that should deviate from the
191 * default styling.
192 * @param defStyleAttr An attribute in the current theme that contains a
193 * reference to a style resource that supplies default values for
194 * the view. Can be 0 to not look for defaults.
195 * @param defStyleRes A resource identifier of a style resource that
196 * supplies default values for the view, used only if
197 * defStyleAttr is 0 or can not be found in the theme. Can be 0
198 * to not look for defaults.
199 */
200 public Switch(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
201 super(context, attrs, defStyleAttr, defStyleRes);
Adam Powell12190b32010-11-28 19:07:53 -0800202
203 mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
Alan Viverette661e6362014-05-12 10:55:37 -0700204
205 final Resources res = getResources();
Adam Powell12190b32010-11-28 19:07:53 -0800206 mTextPaint.density = res.getDisplayMetrics().density;
207 mTextPaint.setCompatibilityScaling(res.getCompatibilityInfo().applicationScale);
208
Alan Viverette617feb92013-09-09 18:09:13 -0700209 final TypedArray a = context.obtainStyledAttributes(
210 attrs, com.android.internal.R.styleable.Switch, defStyleAttr, defStyleRes);
Chet Haase150176d2011-08-26 09:54:06 -0700211 mThumbDrawable = a.getDrawable(com.android.internal.R.styleable.Switch_thumb);
Alan Viveretteb0674052014-09-26 16:12:16 -0700212 if (mThumbDrawable != null) {
213 mThumbDrawable.setCallback(this);
214 }
Chet Haase150176d2011-08-26 09:54:06 -0700215 mTrackDrawable = a.getDrawable(com.android.internal.R.styleable.Switch_track);
Alan Viveretteb0674052014-09-26 16:12:16 -0700216 if (mTrackDrawable != null) {
217 mTrackDrawable.setCallback(this);
218 }
Adam Powell12190b32010-11-28 19:07:53 -0800219 mTextOn = a.getText(com.android.internal.R.styleable.Switch_textOn);
220 mTextOff = a.getText(com.android.internal.R.styleable.Switch_textOff);
Alan Viverette2a37cf8d2014-06-19 17:09:10 -0700221 mShowText = a.getBoolean(com.android.internal.R.styleable.Switch_showText, true);
Adam Powell12190b32010-11-28 19:07:53 -0800222 mThumbTextPadding = a.getDimensionPixelSize(
223 com.android.internal.R.styleable.Switch_thumbTextPadding, 0);
224 mSwitchMinWidth = a.getDimensionPixelSize(
225 com.android.internal.R.styleable.Switch_switchMinWidth, 0);
226 mSwitchPadding = a.getDimensionPixelSize(
227 com.android.internal.R.styleable.Switch_switchPadding, 0);
Alan Viverette661e6362014-05-12 10:55:37 -0700228 mSplitTrack = a.getBoolean(com.android.internal.R.styleable.Switch_splitTrack, false);
Adam Powell12190b32010-11-28 19:07:53 -0800229
Alan Viverette661e6362014-05-12 10:55:37 -0700230 final int appearance = a.getResourceId(
Adam Powell12190b32010-11-28 19:07:53 -0800231 com.android.internal.R.styleable.Switch_switchTextAppearance, 0);
232 if (appearance != 0) {
Chet Haase150176d2011-08-26 09:54:06 -0700233 setSwitchTextAppearance(context, appearance);
Adam Powell12190b32010-11-28 19:07:53 -0800234 }
235 a.recycle();
236
Alan Viverette661e6362014-05-12 10:55:37 -0700237 final ViewConfiguration config = ViewConfiguration.get(context);
Adam Powell12190b32010-11-28 19:07:53 -0800238 mTouchSlop = config.getScaledTouchSlop();
239 mMinFlingVelocity = config.getScaledMinimumFlingVelocity();
240
241 // Refresh display with current params
Gilles Debunnee724ee42011-08-31 11:20:27 -0700242 refreshDrawableState();
Adam Powell12190b32010-11-28 19:07:53 -0800243 setChecked(isChecked());
244 }
245
246 /**
247 * Sets the switch text color, size, style, hint color, and highlight color
248 * from the specified TextAppearance resource.
Adam Powell6c86e1b2012-03-08 15:11:46 -0800249 *
250 * @attr ref android.R.styleable#Switch_switchTextAppearance
Adam Powell12190b32010-11-28 19:07:53 -0800251 */
Chet Haase150176d2011-08-26 09:54:06 -0700252 public void setSwitchTextAppearance(Context context, int resid) {
Adam Powell12190b32010-11-28 19:07:53 -0800253 TypedArray appearance =
Chet Haase150176d2011-08-26 09:54:06 -0700254 context.obtainStyledAttributes(resid,
Adam Powell12190b32010-11-28 19:07:53 -0800255 com.android.internal.R.styleable.TextAppearance);
256
257 ColorStateList colors;
258 int ts;
259
260 colors = appearance.getColorStateList(com.android.internal.R.styleable.
261 TextAppearance_textColor);
262 if (colors != null) {
263 mTextColors = colors;
Chet Haase150176d2011-08-26 09:54:06 -0700264 } else {
265 // If no color set in TextAppearance, default to the view's textColor
266 mTextColors = getTextColors();
Adam Powell12190b32010-11-28 19:07:53 -0800267 }
268
269 ts = appearance.getDimensionPixelSize(com.android.internal.R.styleable.
270 TextAppearance_textSize, 0);
271 if (ts != 0) {
272 if (ts != mTextPaint.getTextSize()) {
273 mTextPaint.setTextSize(ts);
274 requestLayout();
275 }
276 }
277
278 int typefaceIndex, styleIndex;
279
280 typefaceIndex = appearance.getInt(com.android.internal.R.styleable.
281 TextAppearance_typeface, -1);
282 styleIndex = appearance.getInt(com.android.internal.R.styleable.
283 TextAppearance_textStyle, -1);
284
285 setSwitchTypefaceByIndex(typefaceIndex, styleIndex);
286
Daniel Sandler4c3308d2012-04-19 11:04:39 -0400287 boolean allCaps = appearance.getBoolean(com.android.internal.R.styleable.
288 TextAppearance_textAllCaps, false);
289 if (allCaps) {
290 mSwitchTransformationMethod = new AllCapsTransformationMethod(getContext());
291 mSwitchTransformationMethod.setLengthChangesAllowed(true);
292 } else {
293 mSwitchTransformationMethod = null;
294 }
295
Adam Powell12190b32010-11-28 19:07:53 -0800296 appearance.recycle();
297 }
298
299 private void setSwitchTypefaceByIndex(int typefaceIndex, int styleIndex) {
300 Typeface tf = null;
301 switch (typefaceIndex) {
302 case SANS:
303 tf = Typeface.SANS_SERIF;
304 break;
305
306 case SERIF:
307 tf = Typeface.SERIF;
308 break;
309
310 case MONOSPACE:
311 tf = Typeface.MONOSPACE;
312 break;
313 }
314
315 setSwitchTypeface(tf, styleIndex);
316 }
317
318 /**
319 * Sets the typeface and style in which the text should be displayed on the
320 * switch, and turns on the fake bold and italic bits in the Paint if the
321 * Typeface that you provided does not have all the bits in the
322 * style that you specified.
323 */
324 public void setSwitchTypeface(Typeface tf, int style) {
325 if (style > 0) {
326 if (tf == null) {
327 tf = Typeface.defaultFromStyle(style);
328 } else {
329 tf = Typeface.create(tf, style);
330 }
331
332 setSwitchTypeface(tf);
333 // now compute what (if any) algorithmic styling is needed
334 int typefaceStyle = tf != null ? tf.getStyle() : 0;
335 int need = style & ~typefaceStyle;
336 mTextPaint.setFakeBoldText((need & Typeface.BOLD) != 0);
337 mTextPaint.setTextSkewX((need & Typeface.ITALIC) != 0 ? -0.25f : 0);
338 } else {
Victoria Leaseaa0980a2012-06-11 14:46:04 -0700339 mTextPaint.setFakeBoldText(false);
Adam Powell12190b32010-11-28 19:07:53 -0800340 mTextPaint.setTextSkewX(0);
341 setSwitchTypeface(tf);
342 }
343 }
344
345 /**
Chet Haase150176d2011-08-26 09:54:06 -0700346 * Sets the typeface in which the text should be displayed on the switch.
Adam Powell12190b32010-11-28 19:07:53 -0800347 * Note that not all Typeface families actually have bold and italic
348 * variants, so you may need to use
349 * {@link #setSwitchTypeface(Typeface, int)} to get the appearance
350 * that you actually want.
351 *
352 * @attr ref android.R.styleable#TextView_typeface
353 * @attr ref android.R.styleable#TextView_textStyle
354 */
355 public void setSwitchTypeface(Typeface tf) {
356 if (mTextPaint.getTypeface() != tf) {
357 mTextPaint.setTypeface(tf);
358
359 requestLayout();
360 invalidate();
361 }
362 }
363
364 /**
Adam Powell6c86e1b2012-03-08 15:11:46 -0800365 * Set the amount of horizontal padding between the switch and the associated text.
366 *
367 * @param pixels Amount of padding in pixels
368 *
369 * @attr ref android.R.styleable#Switch_switchPadding
370 */
371 public void setSwitchPadding(int pixels) {
372 mSwitchPadding = pixels;
373 requestLayout();
374 }
375
376 /**
377 * Get the amount of horizontal padding between the switch and the associated text.
378 *
379 * @return Amount of padding in pixels
380 *
381 * @attr ref android.R.styleable#Switch_switchPadding
382 */
383 public int getSwitchPadding() {
384 return mSwitchPadding;
385 }
386
387 /**
388 * Set the minimum width of the switch in pixels. The switch's width will be the maximum
389 * of this value and its measured width as determined by the switch drawables and text used.
390 *
391 * @param pixels Minimum width of the switch in pixels
392 *
393 * @attr ref android.R.styleable#Switch_switchMinWidth
394 */
395 public void setSwitchMinWidth(int pixels) {
396 mSwitchMinWidth = pixels;
397 requestLayout();
398 }
399
400 /**
401 * Get the minimum width of the switch in pixels. The switch's width will be the maximum
402 * of this value and its measured width as determined by the switch drawables and text used.
403 *
404 * @return Minimum width of the switch in pixels
405 *
406 * @attr ref android.R.styleable#Switch_switchMinWidth
407 */
408 public int getSwitchMinWidth() {
409 return mSwitchMinWidth;
410 }
411
412 /**
413 * Set the horizontal padding around the text drawn on the switch itself.
414 *
415 * @param pixels Horizontal padding for switch thumb text in pixels
416 *
417 * @attr ref android.R.styleable#Switch_thumbTextPadding
418 */
419 public void setThumbTextPadding(int pixels) {
420 mThumbTextPadding = pixels;
421 requestLayout();
422 }
423
424 /**
425 * Get the horizontal padding around the text drawn on the switch itself.
426 *
427 * @return Horizontal padding for switch thumb text in pixels
428 *
429 * @attr ref android.R.styleable#Switch_thumbTextPadding
430 */
431 public int getThumbTextPadding() {
432 return mThumbTextPadding;
433 }
434
435 /**
436 * Set the drawable used for the track that the switch slides within.
437 *
438 * @param track Track drawable
439 *
440 * @attr ref android.R.styleable#Switch_track
441 */
442 public void setTrackDrawable(Drawable track) {
Alan Viveretteb0674052014-09-26 16:12:16 -0700443 if (mTrackDrawable != null) {
444 mTrackDrawable.setCallback(null);
445 }
Adam Powell6c86e1b2012-03-08 15:11:46 -0800446 mTrackDrawable = track;
Alan Viveretteb0674052014-09-26 16:12:16 -0700447 if (track != null) {
448 track.setCallback(this);
449 }
Adam Powell6c86e1b2012-03-08 15:11:46 -0800450 requestLayout();
451 }
452
453 /**
Adam Powelld9c7be62012-03-08 19:43:43 -0800454 * Set the drawable used for the track that the switch slides within.
455 *
Adam Powelldca510e2012-03-08 20:06:39 -0800456 * @param resId Resource ID of a track drawable
Adam Powelld9c7be62012-03-08 19:43:43 -0800457 *
458 * @attr ref android.R.styleable#Switch_track
459 */
460 public void setTrackResource(int resId) {
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800461 setTrackDrawable(getContext().getDrawable(resId));
Adam Powelld9c7be62012-03-08 19:43:43 -0800462 }
463
464 /**
Adam Powell6c86e1b2012-03-08 15:11:46 -0800465 * Get the drawable used for the track that the switch slides within.
466 *
467 * @return Track drawable
468 *
469 * @attr ref android.R.styleable#Switch_track
470 */
471 public Drawable getTrackDrawable() {
472 return mTrackDrawable;
473 }
474
475 /**
476 * Set the drawable used for the switch "thumb" - the piece that the user
477 * can physically touch and drag along the track.
478 *
479 * @param thumb Thumb drawable
480 *
481 * @attr ref android.R.styleable#Switch_thumb
482 */
483 public void setThumbDrawable(Drawable thumb) {
Alan Viveretteb0674052014-09-26 16:12:16 -0700484 if (mThumbDrawable != null) {
485 mThumbDrawable.setCallback(null);
486 }
Adam Powell6c86e1b2012-03-08 15:11:46 -0800487 mThumbDrawable = thumb;
Alan Viveretteb0674052014-09-26 16:12:16 -0700488 if (thumb != null) {
489 thumb.setCallback(this);
490 }
Adam Powell6c86e1b2012-03-08 15:11:46 -0800491 requestLayout();
492 }
493
494 /**
Adam Powelld9c7be62012-03-08 19:43:43 -0800495 * Set the drawable used for the switch "thumb" - the piece that the user
496 * can physically touch and drag along the track.
497 *
Adam Powelldca510e2012-03-08 20:06:39 -0800498 * @param resId Resource ID of a thumb drawable
Adam Powelld9c7be62012-03-08 19:43:43 -0800499 *
500 * @attr ref android.R.styleable#Switch_thumb
501 */
502 public void setThumbResource(int resId) {
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800503 setThumbDrawable(getContext().getDrawable(resId));
Adam Powelld9c7be62012-03-08 19:43:43 -0800504 }
505
506 /**
Adam Powell6c86e1b2012-03-08 15:11:46 -0800507 * Get the drawable used for the switch "thumb" - the piece that the user
508 * can physically touch and drag along the track.
509 *
510 * @return Thumb drawable
511 *
512 * @attr ref android.R.styleable#Switch_thumb
513 */
514 public Drawable getThumbDrawable() {
515 return mThumbDrawable;
516 }
517
518 /**
Alan Viverette661e6362014-05-12 10:55:37 -0700519 * Specifies whether the track should be split by the thumb. When true,
520 * the thumb's optical bounds will be clipped out of the track drawable,
521 * then the thumb will be drawn into the resulting gap.
522 *
523 * @param splitTrack Whether the track should be split by the thumb
524 *
525 * @attr ref android.R.styleable#Switch_splitTrack
526 */
527 public void setSplitTrack(boolean splitTrack) {
528 mSplitTrack = splitTrack;
529 invalidate();
530 }
531
532 /**
533 * Returns whether the track should be split by the thumb.
534 *
535 * @attr ref android.R.styleable#Switch_splitTrack
536 */
537 public boolean getSplitTrack() {
538 return mSplitTrack;
539 }
540
541 /**
Chet Haase150176d2011-08-26 09:54:06 -0700542 * Returns the text displayed when the button is in the checked state.
Adam Powell6c86e1b2012-03-08 15:11:46 -0800543 *
544 * @attr ref android.R.styleable#Switch_textOn
Adam Powell12190b32010-11-28 19:07:53 -0800545 */
546 public CharSequence getTextOn() {
547 return mTextOn;
548 }
549
550 /**
Chet Haase150176d2011-08-26 09:54:06 -0700551 * Sets the text displayed when the button is in the checked state.
Adam Powell6c86e1b2012-03-08 15:11:46 -0800552 *
553 * @attr ref android.R.styleable#Switch_textOn
Adam Powell12190b32010-11-28 19:07:53 -0800554 */
555 public void setTextOn(CharSequence textOn) {
556 mTextOn = textOn;
557 requestLayout();
558 }
559
560 /**
Chet Haase150176d2011-08-26 09:54:06 -0700561 * Returns the text displayed when the button is not in the checked state.
Adam Powell6c86e1b2012-03-08 15:11:46 -0800562 *
563 * @attr ref android.R.styleable#Switch_textOff
Adam Powell12190b32010-11-28 19:07:53 -0800564 */
565 public CharSequence getTextOff() {
566 return mTextOff;
567 }
568
569 /**
Chet Haase150176d2011-08-26 09:54:06 -0700570 * Sets the text displayed when the button is not in the checked state.
Adam Powell6c86e1b2012-03-08 15:11:46 -0800571 *
572 * @attr ref android.R.styleable#Switch_textOff
Adam Powell12190b32010-11-28 19:07:53 -0800573 */
574 public void setTextOff(CharSequence textOff) {
575 mTextOff = textOff;
576 requestLayout();
577 }
578
Alan Viverette2a37cf8d2014-06-19 17:09:10 -0700579 /**
580 * Sets whether the on/off text should be displayed.
581 *
582 * @param showText {@code true} to display on/off text
Alan Viverette0c0dde72014-07-30 13:29:39 -0700583 * @attr ref android.R.styleable#Switch_showText
Alan Viverette2a37cf8d2014-06-19 17:09:10 -0700584 */
585 public void setShowText(boolean showText) {
586 if (mShowText != showText) {
587 mShowText = showText;
588 requestLayout();
589 }
590 }
591
592 /**
593 * @return whether the on/off text should be displayed
Alan Viverette0c0dde72014-07-30 13:29:39 -0700594 * @attr ref android.R.styleable#Switch_showText
Alan Viverette2a37cf8d2014-06-19 17:09:10 -0700595 */
596 public boolean getShowText() {
597 return mShowText;
598 }
599
Adam Powell12190b32010-11-28 19:07:53 -0800600 @Override
601 public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Alan Viverette2a37cf8d2014-06-19 17:09:10 -0700602 if (mShowText) {
603 if (mOnLayout == null) {
604 mOnLayout = makeLayout(mTextOn);
605 }
Alan Viverette5876ff42014-03-03 17:40:46 -0800606
Alan Viverette2a37cf8d2014-06-19 17:09:10 -0700607 if (mOffLayout == null) {
608 mOffLayout = makeLayout(mTextOff);
609 }
Adam Powell12190b32010-11-28 19:07:53 -0800610 }
611
Alan Viverette9b38f6c2014-07-30 02:39:07 +0000612 final Rect padding = mTempRect;
Alan Viverette0c0dde72014-07-30 13:29:39 -0700613 final int thumbWidth;
614 final int thumbHeight;
615 if (mThumbDrawable != null) {
616 // Cached thumb width does not include padding.
617 mThumbDrawable.getPadding(padding);
618 thumbWidth = mThumbDrawable.getIntrinsicWidth() - padding.left - padding.right;
619 thumbHeight = mThumbDrawable.getIntrinsicHeight();
620 } else {
621 thumbWidth = 0;
622 thumbHeight = 0;
623 }
624
625 final int maxTextWidth;
626 if (mShowText) {
627 maxTextWidth = Math.max(mOnLayout.getWidth(), mOffLayout.getWidth())
628 + mThumbTextPadding * 2;
629 } else {
630 maxTextWidth = 0;
631 }
632
633 mThumbWidth = Math.max(maxTextWidth, thumbWidth);
634
635 final int trackHeight;
Alan Viverette4d065a02014-07-11 15:28:38 -0700636 if (mTrackDrawable != null) {
637 mTrackDrawable.getPadding(padding);
638 trackHeight = mTrackDrawable.getIntrinsicHeight();
639 } else {
640 padding.setEmpty();
641 trackHeight = 0;
642 }
643
Alan Viverette0c0dde72014-07-30 13:29:39 -0700644 // Adjust left and right padding to ensure there's enough room for the
645 // thumb's padding (when present).
646 int paddingLeft = padding.left;
647 int paddingRight = padding.right;
Alan Viverette4d065a02014-07-11 15:28:38 -0700648 if (mThumbDrawable != null) {
Alan Viverette0c0dde72014-07-30 13:29:39 -0700649 final Insets inset = mThumbDrawable.getOpticalInsets();
650 paddingLeft = Math.max(paddingLeft, inset.left);
651 paddingRight = Math.max(paddingRight, inset.right);
Alan Viverette4d065a02014-07-11 15:28:38 -0700652 }
Alan Viverette5876ff42014-03-03 17:40:46 -0800653
Adam Powell12190b32010-11-28 19:07:53 -0800654 final int switchWidth = Math.max(mSwitchMinWidth,
Alan Viverette0c0dde72014-07-30 13:29:39 -0700655 2 * mThumbWidth + paddingLeft + paddingRight);
Alan Viverette4d065a02014-07-11 15:28:38 -0700656 final int switchHeight = Math.max(trackHeight, thumbHeight);
Adam Powell12190b32010-11-28 19:07:53 -0800657 mSwitchWidth = switchWidth;
658 mSwitchHeight = switchHeight;
659
660 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
Alan Viverette4d065a02014-07-11 15:28:38 -0700661
Adam Powell12190b32010-11-28 19:07:53 -0800662 final int measuredHeight = getMeasuredHeight();
663 if (measuredHeight < switchHeight) {
Dianne Hackborn189ee182010-12-02 21:48:53 -0800664 setMeasuredDimension(getMeasuredWidthAndState(), switchHeight);
Adam Powell12190b32010-11-28 19:07:53 -0800665 }
666 }
667
Alan Viverettea54956a2015-01-07 16:05:02 -0800668 /** @hide */
Svetoslav Ganov63bce032011-07-23 19:52:17 -0700669 @Override
Alan Viverettea54956a2015-01-07 16:05:02 -0800670 public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
671 super.onPopulateAccessibilityEventInternal(event);
Alan Viverette2a37cf8d2014-06-19 17:09:10 -0700672
673 final CharSequence text = isChecked() ? mTextOn : mTextOff;
674 if (text != null) {
675 event.getText().add(text);
Svetoslav Ganov76502592011-07-29 10:44:59 -0700676 }
Svetoslav Ganov63bce032011-07-23 19:52:17 -0700677 }
678
Adam Powell12190b32010-11-28 19:07:53 -0800679 private Layout makeLayout(CharSequence text) {
Daniel Sandler4c3308d2012-04-19 11:04:39 -0400680 final CharSequence transformed = (mSwitchTransformationMethod != null)
681 ? mSwitchTransformationMethod.getTransformation(text, this)
682 : text;
683
684 return new StaticLayout(transformed, mTextPaint,
685 (int) Math.ceil(Layout.getDesiredWidth(transformed, mTextPaint)),
Adam Powell12190b32010-11-28 19:07:53 -0800686 Layout.Alignment.ALIGN_NORMAL, 1.f, 0, true);
687 }
688
689 /**
690 * @return true if (x, y) is within the target area of the switch thumb
691 */
692 private boolean hitThumb(float x, float y) {
Alan Viverette01a09632014-12-08 13:02:06 -0800693 if (mThumbDrawable == null) {
694 return false;
695 }
696
Alan Viverettecc2688d2013-09-17 17:00:12 -0700697 // Relies on mTempRect, MUST be called first!
698 final int thumbOffset = getThumbOffset();
699
Adam Powell12190b32010-11-28 19:07:53 -0800700 mThumbDrawable.getPadding(mTempRect);
701 final int thumbTop = mSwitchTop - mTouchSlop;
Alan Viverettecc2688d2013-09-17 17:00:12 -0700702 final int thumbLeft = mSwitchLeft + thumbOffset - mTouchSlop;
Adam Powell12190b32010-11-28 19:07:53 -0800703 final int thumbRight = thumbLeft + mThumbWidth +
704 mTempRect.left + mTempRect.right + mTouchSlop;
705 final int thumbBottom = mSwitchBottom + mTouchSlop;
706 return x > thumbLeft && x < thumbRight && y > thumbTop && y < thumbBottom;
707 }
708
709 @Override
710 public boolean onTouchEvent(MotionEvent ev) {
711 mVelocityTracker.addMovement(ev);
712 final int action = ev.getActionMasked();
713 switch (action) {
714 case MotionEvent.ACTION_DOWN: {
715 final float x = ev.getX();
716 final float y = ev.getY();
Gilles Debunnec2ab0d62011-06-13 12:52:48 -0700717 if (isEnabled() && hitThumb(x, y)) {
Adam Powell12190b32010-11-28 19:07:53 -0800718 mTouchMode = TOUCH_MODE_DOWN;
719 mTouchX = x;
720 mTouchY = y;
721 }
722 break;
723 }
724
725 case MotionEvent.ACTION_MOVE: {
726 switch (mTouchMode) {
727 case TOUCH_MODE_IDLE:
728 // Didn't target the thumb, treat normally.
729 break;
730
731 case TOUCH_MODE_DOWN: {
732 final float x = ev.getX();
733 final float y = ev.getY();
734 if (Math.abs(x - mTouchX) > mTouchSlop ||
735 Math.abs(y - mTouchY) > mTouchSlop) {
736 mTouchMode = TOUCH_MODE_DRAGGING;
737 getParent().requestDisallowInterceptTouchEvent(true);
738 mTouchX = x;
739 mTouchY = y;
740 return true;
741 }
742 break;
743 }
744
745 case TOUCH_MODE_DRAGGING: {
746 final float x = ev.getX();
Alan Viverettecc2688d2013-09-17 17:00:12 -0700747 final int thumbScrollRange = getThumbScrollRange();
748 final float thumbScrollOffset = x - mTouchX;
749 float dPos;
750 if (thumbScrollRange != 0) {
751 dPos = thumbScrollOffset / thumbScrollRange;
752 } else {
753 // If the thumb scroll range is empty, just use the
754 // movement direction to snap on or off.
755 dPos = thumbScrollOffset > 0 ? 1 : -1;
756 }
757 if (isLayoutRtl()) {
758 dPos = -dPos;
759 }
760 final float newPos = MathUtils.constrain(mThumbPosition + dPos, 0, 1);
Adam Powell12190b32010-11-28 19:07:53 -0800761 if (newPos != mThumbPosition) {
Adam Powell12190b32010-11-28 19:07:53 -0800762 mTouchX = x;
Alan Viverettecc2688d2013-09-17 17:00:12 -0700763 setThumbPosition(newPos);
Adam Powell12190b32010-11-28 19:07:53 -0800764 }
765 return true;
766 }
767 }
768 break;
769 }
770
771 case MotionEvent.ACTION_UP:
772 case MotionEvent.ACTION_CANCEL: {
773 if (mTouchMode == TOUCH_MODE_DRAGGING) {
774 stopDrag(ev);
Alan Viverettead2f8e32014-05-16 13:28:33 -0700775 // Allow super class to handle pressed state, etc.
776 super.onTouchEvent(ev);
Adam Powell12190b32010-11-28 19:07:53 -0800777 return true;
778 }
779 mTouchMode = TOUCH_MODE_IDLE;
780 mVelocityTracker.clear();
781 break;
782 }
783 }
784
785 return super.onTouchEvent(ev);
786 }
787
788 private void cancelSuperTouch(MotionEvent ev) {
789 MotionEvent cancel = MotionEvent.obtain(ev);
790 cancel.setAction(MotionEvent.ACTION_CANCEL);
791 super.onTouchEvent(cancel);
792 cancel.recycle();
793 }
794
795 /**
796 * Called from onTouchEvent to end a drag operation.
797 *
798 * @param ev Event that triggered the end of drag mode - ACTION_UP or ACTION_CANCEL
799 */
800 private void stopDrag(MotionEvent ev) {
801 mTouchMode = TOUCH_MODE_IDLE;
Adam Powell12190b32010-11-28 19:07:53 -0800802
Alan Viverette86453ff2013-09-26 14:46:08 -0700803 // Commit the change if the event is up and not canceled and the switch
804 // has not been disabled during the drag.
805 final boolean commitChange = ev.getAction() == MotionEvent.ACTION_UP && isEnabled();
Alan Viveretted4e77902014-10-27 17:50:51 -0700806 final boolean oldState = isChecked();
Alan Viverette86453ff2013-09-26 14:46:08 -0700807 final boolean newState;
Adam Powell12190b32010-11-28 19:07:53 -0800808 if (commitChange) {
Adam Powell12190b32010-11-28 19:07:53 -0800809 mVelocityTracker.computeCurrentVelocity(1000);
Alan Viverette86453ff2013-09-26 14:46:08 -0700810 final float xvel = mVelocityTracker.getXVelocity();
Adam Powell12190b32010-11-28 19:07:53 -0800811 if (Math.abs(xvel) > mMinFlingVelocity) {
Fabrice Di Meglio28efba32012-06-01 16:52:31 -0700812 newState = isLayoutRtl() ? (xvel < 0) : (xvel > 0);
Adam Powell12190b32010-11-28 19:07:53 -0800813 } else {
814 newState = getTargetCheckedState();
815 }
Adam Powell12190b32010-11-28 19:07:53 -0800816 } else {
Alan Viveretted4e77902014-10-27 17:50:51 -0700817 newState = oldState;
Adam Powell12190b32010-11-28 19:07:53 -0800818 }
Alan Viverette86453ff2013-09-26 14:46:08 -0700819
Alan Viveretted4e77902014-10-27 17:50:51 -0700820 if (newState != oldState) {
821 playSoundEffect(SoundEffectConstants.CLICK);
822 setChecked(newState);
823 }
824
Alan Viverette86453ff2013-09-26 14:46:08 -0700825 cancelSuperTouch(ev);
Adam Powell12190b32010-11-28 19:07:53 -0800826 }
827
828 private void animateThumbToCheckedState(boolean newCheckedState) {
Alan Viverettecc2688d2013-09-17 17:00:12 -0700829 final float targetPosition = newCheckedState ? 1 : 0;
830 mPositionAnimator = ObjectAnimator.ofFloat(this, THUMB_POS, targetPosition);
831 mPositionAnimator.setDuration(THUMB_ANIMATION_DURATION);
832 mPositionAnimator.setAutoCancel(true);
833 mPositionAnimator.start();
834 }
835
836 private void cancelPositionAnimator() {
837 if (mPositionAnimator != null) {
838 mPositionAnimator.cancel();
839 }
Adam Powell12190b32010-11-28 19:07:53 -0800840 }
841
842 private boolean getTargetCheckedState() {
Alan Viverettecc2688d2013-09-17 17:00:12 -0700843 return mThumbPosition > 0.5f;
Fabrice Di Meglio28efba32012-06-01 16:52:31 -0700844 }
845
Alan Viverettecc2688d2013-09-17 17:00:12 -0700846 /**
847 * Sets the thumb position as a decimal value between 0 (off) and 1 (on).
848 *
849 * @param position new position between [0,1]
850 */
851 private void setThumbPosition(float position) {
852 mThumbPosition = position;
853 invalidate();
854 }
855
856 @Override
857 public void toggle() {
Alan Viverette86453ff2013-09-26 14:46:08 -0700858 setChecked(!isChecked());
Adam Powell12190b32010-11-28 19:07:53 -0800859 }
860
861 @Override
862 public void setChecked(boolean checked) {
863 super.setChecked(checked);
Alan Viverettecc2688d2013-09-17 17:00:12 -0700864
Alan Viverette467d6292014-08-12 15:13:19 -0700865 // Calling the super method may result in setChecked() getting called
866 // recursively with a different value, so load the REAL value...
867 checked = isChecked();
868
Alan Viverette86453ff2013-09-26 14:46:08 -0700869 if (isAttachedToWindow() && isLaidOut()) {
870 animateThumbToCheckedState(checked);
871 } else {
872 // Immediately move the thumb to the new position.
873 cancelPositionAnimator();
874 setThumbPosition(checked ? 1 : 0);
875 }
Adam Powell12190b32010-11-28 19:07:53 -0800876 }
877
878 @Override
879 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
880 super.onLayout(changed, left, top, right, bottom);
881
Alan Viverette0c0dde72014-07-30 13:29:39 -0700882 int opticalInsetLeft = 0;
883 int opticalInsetRight = 0;
884 if (mThumbDrawable != null) {
885 final Rect trackPadding = mTempRect;
886 if (mTrackDrawable != null) {
887 mTrackDrawable.getPadding(trackPadding);
888 } else {
889 trackPadding.setEmpty();
890 }
Fabrice Di Meglio28efba32012-06-01 16:52:31 -0700891
Alan Viverette0c0dde72014-07-30 13:29:39 -0700892 final Insets insets = mThumbDrawable.getOpticalInsets();
893 opticalInsetLeft = Math.max(0, insets.left - trackPadding.left);
894 opticalInsetRight = Math.max(0, insets.right - trackPadding.right);
Alan Viverette8bb39902014-07-29 17:22:30 -0700895 }
896
Alan Viverette0c0dde72014-07-30 13:29:39 -0700897 final int switchRight;
898 final int switchLeft;
899 if (isLayoutRtl()) {
900 switchLeft = getPaddingLeft() + opticalInsetLeft;
901 switchRight = switchLeft + mSwitchWidth - opticalInsetLeft - opticalInsetRight;
902 } else {
903 switchRight = getWidth() - getPaddingRight() - opticalInsetRight;
904 switchLeft = switchRight - mSwitchWidth + opticalInsetLeft + opticalInsetRight;
905 }
906
907 final int switchTop;
908 final int switchBottom;
Adam Powell12190b32010-11-28 19:07:53 -0800909 switch (getGravity() & Gravity.VERTICAL_GRAVITY_MASK) {
910 default:
911 case Gravity.TOP:
912 switchTop = getPaddingTop();
913 switchBottom = switchTop + mSwitchHeight;
914 break;
915
916 case Gravity.CENTER_VERTICAL:
917 switchTop = (getPaddingTop() + getHeight() - getPaddingBottom()) / 2 -
918 mSwitchHeight / 2;
919 switchBottom = switchTop + mSwitchHeight;
920 break;
921
922 case Gravity.BOTTOM:
923 switchBottom = getHeight() - getPaddingBottom();
924 switchTop = switchBottom - mSwitchHeight;
925 break;
926 }
927
928 mSwitchLeft = switchLeft;
929 mSwitchTop = switchTop;
930 mSwitchBottom = switchBottom;
931 mSwitchRight = switchRight;
932 }
933
934 @Override
Alan Viverettead2f8e32014-05-16 13:28:33 -0700935 public void draw(Canvas c) {
Alan Viverette4d065a02014-07-11 15:28:38 -0700936 final Rect padding = mTempRect;
Alan Viverette5876ff42014-03-03 17:40:46 -0800937 final int switchLeft = mSwitchLeft;
938 final int switchTop = mSwitchTop;
939 final int switchRight = mSwitchRight;
940 final int switchBottom = mSwitchBottom;
Alan Viverette0c0dde72014-07-30 13:29:39 -0700941
942 int thumbInitialLeft = switchLeft + getThumbOffset();
943
944 final Insets thumbInsets;
945 if (mThumbDrawable != null) {
946 thumbInsets = mThumbDrawable.getOpticalInsets();
947 } else {
948 thumbInsets = Insets.NONE;
Alan Viverette8bb39902014-07-29 17:22:30 -0700949 }
Alan Viverettecc2688d2013-09-17 17:00:12 -0700950
Alan Viverette0c0dde72014-07-30 13:29:39 -0700951 // Layout the track.
952 if (mTrackDrawable != null) {
953 mTrackDrawable.getPadding(padding);
Alan Viverette9b38f6c2014-07-30 02:39:07 +0000954
Alan Viverette0c0dde72014-07-30 13:29:39 -0700955 // Adjust thumb position for track padding.
956 thumbInitialLeft += padding.left;
957
958 // If necessary, offset by the optical insets of the thumb asset.
959 int trackLeft = switchLeft;
960 int trackTop = switchTop;
961 int trackRight = switchRight;
962 int trackBottom = switchBottom;
963 if (thumbInsets != Insets.NONE) {
964 if (thumbInsets.left > padding.left) {
965 trackLeft += thumbInsets.left - padding.left;
966 }
967 if (thumbInsets.top > padding.top) {
968 trackTop += thumbInsets.top - padding.top;
969 }
970 if (thumbInsets.right > padding.right) {
971 trackRight -= thumbInsets.right - padding.right;
972 }
973 if (thumbInsets.bottom > padding.bottom) {
974 trackBottom -= thumbInsets.bottom - padding.bottom;
975 }
976 }
977 mTrackDrawable.setBounds(trackLeft, trackTop, trackRight, trackBottom);
978 }
Alan Viverette9b38f6c2014-07-30 02:39:07 +0000979
Alan Viverette661e6362014-05-12 10:55:37 -0700980 // Layout the thumb.
Alan Viverette4d065a02014-07-11 15:28:38 -0700981 if (mThumbDrawable != null) {
982 mThumbDrawable.getPadding(padding);
Alan Viverette0c0dde72014-07-30 13:29:39 -0700983
984 final int thumbLeft = thumbInitialLeft - padding.left;
985 final int thumbRight = thumbInitialLeft + mThumbWidth + padding.right;
Alan Viverette4d065a02014-07-11 15:28:38 -0700986 mThumbDrawable.setBounds(thumbLeft, switchTop, thumbRight, switchBottom);
Alan Viverette61956602014-04-22 19:07:06 -0700987
Alan Viverette4d065a02014-07-11 15:28:38 -0700988 final Drawable background = getBackground();
989 if (background != null) {
990 background.setHotspotBounds(thumbLeft, switchTop, thumbRight, switchBottom);
991 }
Alan Viverette61956602014-04-22 19:07:06 -0700992 }
993
Alan Viverettead2f8e32014-05-16 13:28:33 -0700994 // Draw the background.
995 super.draw(c);
996 }
997
998 @Override
999 protected void onDraw(Canvas canvas) {
Alan Viverette61956602014-04-22 19:07:06 -07001000 super.onDraw(canvas);
1001
Alan Viverette4d065a02014-07-11 15:28:38 -07001002 final Rect padding = mTempRect;
Alan Viverettead2f8e32014-05-16 13:28:33 -07001003 final Drawable trackDrawable = mTrackDrawable;
Alan Viverette4d065a02014-07-11 15:28:38 -07001004 if (trackDrawable != null) {
1005 trackDrawable.getPadding(padding);
1006 } else {
1007 padding.setEmpty();
1008 }
Alan Viverettead2f8e32014-05-16 13:28:33 -07001009
1010 final int switchTop = mSwitchTop;
1011 final int switchBottom = mSwitchBottom;
Alan Viverette4d065a02014-07-11 15:28:38 -07001012 final int switchInnerTop = switchTop + padding.top;
Alan Viverette4d065a02014-07-11 15:28:38 -07001013 final int switchInnerBottom = switchBottom - padding.bottom;
Alan Viverettead2f8e32014-05-16 13:28:33 -07001014
Alan Viverette4d065a02014-07-11 15:28:38 -07001015 final Drawable thumbDrawable = mThumbDrawable;
1016 if (trackDrawable != null) {
1017 if (mSplitTrack && thumbDrawable != null) {
1018 final Insets insets = thumbDrawable.getOpticalInsets();
1019 thumbDrawable.copyBounds(padding);
1020 padding.left += insets.left;
1021 padding.right -= insets.right;
Alan Viverette661e6362014-05-12 10:55:37 -07001022
Alan Viverette4d065a02014-07-11 15:28:38 -07001023 final int saveCount = canvas.save();
1024 canvas.clipRect(padding, Op.DIFFERENCE);
1025 trackDrawable.draw(canvas);
1026 canvas.restoreToCount(saveCount);
1027 } else {
1028 trackDrawable.draw(canvas);
1029 }
Alan Viverette661e6362014-05-12 10:55:37 -07001030 }
Alan Viverette61956602014-04-22 19:07:06 -07001031
1032 final int saveCount = canvas.save();
Alan Viverette4d065a02014-07-11 15:28:38 -07001033
1034 if (thumbDrawable != null) {
Alan Viverette4d065a02014-07-11 15:28:38 -07001035 thumbDrawable.draw(canvas);
1036 }
Adam Powell12190b32010-11-28 19:07:53 -08001037
Alan Viverette5876ff42014-03-03 17:40:46 -08001038 final Layout switchText = getTargetCheckedState() ? mOnLayout : mOffLayout;
Fabrice Di Megliobe06e322012-09-11 17:42:45 -07001039 if (switchText != null) {
Alan Viverette661e6362014-05-12 10:55:37 -07001040 final int drawableState[] = getDrawableState();
1041 if (mTextColors != null) {
1042 mTextPaint.setColor(mTextColors.getColorForState(drawableState, 0));
1043 }
1044 mTextPaint.drawableState = drawableState;
1045
Alan Viverette4d065a02014-07-11 15:28:38 -07001046 final int cX;
1047 if (thumbDrawable != null) {
1048 final Rect bounds = thumbDrawable.getBounds();
1049 cX = bounds.left + bounds.right;
1050 } else {
Alan Viverettedec17292014-07-12 00:26:36 -07001051 cX = getWidth();
Alan Viverette4d065a02014-07-11 15:28:38 -07001052 }
1053
1054 final int left = cX / 2 - switchText.getWidth() / 2;
Alan Viverette5876ff42014-03-03 17:40:46 -08001055 final int top = (switchInnerTop + switchInnerBottom) / 2 - switchText.getHeight() / 2;
1056 canvas.translate(left, top);
Fabrice Di Megliobe06e322012-09-11 17:42:45 -07001057 switchText.draw(canvas);
1058 }
Adam Powell12190b32010-11-28 19:07:53 -08001059
Alan Viverette5876ff42014-03-03 17:40:46 -08001060 canvas.restoreToCount(saveCount);
Adam Powell12190b32010-11-28 19:07:53 -08001061 }
1062
1063 @Override
Fabrice Di Meglio28efba32012-06-01 16:52:31 -07001064 public int getCompoundPaddingLeft() {
1065 if (!isLayoutRtl()) {
1066 return super.getCompoundPaddingLeft();
1067 }
1068 int padding = super.getCompoundPaddingLeft() + mSwitchWidth;
1069 if (!TextUtils.isEmpty(getText())) {
1070 padding += mSwitchPadding;
1071 }
1072 return padding;
1073 }
1074
1075 @Override
Adam Powell12190b32010-11-28 19:07:53 -08001076 public int getCompoundPaddingRight() {
Fabrice Di Meglio28efba32012-06-01 16:52:31 -07001077 if (isLayoutRtl()) {
1078 return super.getCompoundPaddingRight();
1079 }
Adam Powell12190b32010-11-28 19:07:53 -08001080 int padding = super.getCompoundPaddingRight() + mSwitchWidth;
1081 if (!TextUtils.isEmpty(getText())) {
1082 padding += mSwitchPadding;
1083 }
1084 return padding;
1085 }
1086
Alan Viverettecc2688d2013-09-17 17:00:12 -07001087 /**
1088 * Translates thumb position to offset according to current RTL setting and
Alan Viverette0c0dde72014-07-30 13:29:39 -07001089 * thumb scroll range. Accounts for both track and thumb padding.
Alan Viverettecc2688d2013-09-17 17:00:12 -07001090 *
1091 * @return thumb offset
1092 */
1093 private int getThumbOffset() {
1094 final float thumbPosition;
1095 if (isLayoutRtl()) {
1096 thumbPosition = 1 - mThumbPosition;
1097 } else {
1098 thumbPosition = mThumbPosition;
1099 }
1100 return (int) (thumbPosition * getThumbScrollRange() + 0.5f);
1101 }
1102
Adam Powell12190b32010-11-28 19:07:53 -08001103 private int getThumbScrollRange() {
Alan Viverette4d065a02014-07-11 15:28:38 -07001104 if (mTrackDrawable != null) {
Alan Viverette0c0dde72014-07-30 13:29:39 -07001105 final Rect padding = mTempRect;
1106 mTrackDrawable.getPadding(padding);
1107
1108 final Insets insets;
1109 if (mThumbDrawable != null) {
1110 insets = mThumbDrawable.getOpticalInsets();
1111 } else {
1112 insets = Insets.NONE;
1113 }
1114
1115 return mSwitchWidth - mThumbWidth - padding.left - padding.right
1116 - insets.left - insets.right;
Alan Viverette4d065a02014-07-11 15:28:38 -07001117 } else {
Adam Powell12190b32010-11-28 19:07:53 -08001118 return 0;
1119 }
Adam Powell12190b32010-11-28 19:07:53 -08001120 }
1121
1122 @Override
1123 protected int[] onCreateDrawableState(int extraSpace) {
1124 final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
1125 if (isChecked()) {
1126 mergeDrawableStates(drawableState, CHECKED_STATE_SET);
1127 }
1128 return drawableState;
1129 }
1130
1131 @Override
1132 protected void drawableStateChanged() {
1133 super.drawableStateChanged();
1134
Alan Viverette661e6362014-05-12 10:55:37 -07001135 final int[] myDrawableState = getDrawableState();
Adam Powell12190b32010-11-28 19:07:53 -08001136
Alan Viverette2356c5e2014-05-22 22:43:59 -07001137 if (mThumbDrawable != null) {
1138 mThumbDrawable.setState(myDrawableState);
Alan Viverette661e6362014-05-12 10:55:37 -07001139 }
1140
1141 if (mTrackDrawable != null) {
1142 mTrackDrawable.setState(myDrawableState);
1143 }
Adam Powell12190b32010-11-28 19:07:53 -08001144
1145 invalidate();
1146 }
1147
Alan Viverettecebc6ba2014-06-13 15:52:13 -07001148 @Override
Alan Viverette8de14942014-06-18 18:05:15 -07001149 public void drawableHotspotChanged(float x, float y) {
1150 super.drawableHotspotChanged(x, y);
Alan Viverettecebc6ba2014-06-13 15:52:13 -07001151
1152 if (mThumbDrawable != null) {
1153 mThumbDrawable.setHotspot(x, y);
1154 }
1155
1156 if (mTrackDrawable != null) {
1157 mTrackDrawable.setHotspot(x, y);
1158 }
1159 }
1160
Adam Powell12190b32010-11-28 19:07:53 -08001161 @Override
1162 protected boolean verifyDrawable(Drawable who) {
1163 return super.verifyDrawable(who) || who == mThumbDrawable || who == mTrackDrawable;
1164 }
1165
1166 @Override
1167 public void jumpDrawablesToCurrentState() {
1168 super.jumpDrawablesToCurrentState();
Alan Viverette4d065a02014-07-11 15:28:38 -07001169
1170 if (mThumbDrawable != null) {
1171 mThumbDrawable.jumpToCurrentState();
1172 }
1173
1174 if (mTrackDrawable != null) {
1175 mTrackDrawable.jumpToCurrentState();
1176 }
1177
1178 if (mPositionAnimator != null && mPositionAnimator.isRunning()) {
1179 mPositionAnimator.end();
1180 mPositionAnimator = null;
1181 }
Adam Powell12190b32010-11-28 19:07:53 -08001182 }
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -08001183
Alan Viverettea54956a2015-01-07 16:05:02 -08001184 /** @hide */
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -08001185 @Override
Alan Viverettea54956a2015-01-07 16:05:02 -08001186 public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
1187 super.onInitializeAccessibilityEventInternal(event);
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -08001188 event.setClassName(Switch.class.getName());
1189 }
1190
Alan Viverettea54956a2015-01-07 16:05:02 -08001191 /** @hide */
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -08001192 @Override
Alan Viverettea54956a2015-01-07 16:05:02 -08001193 public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
1194 super.onInitializeAccessibilityNodeInfoInternal(info);
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -08001195 info.setClassName(Switch.class.getName());
Svetoslav Ganov78bcc152012-04-12 17:17:19 -07001196 CharSequence switchText = isChecked() ? mTextOn : mTextOff;
1197 if (!TextUtils.isEmpty(switchText)) {
1198 CharSequence oldText = info.getText();
1199 if (TextUtils.isEmpty(oldText)) {
1200 info.setText(switchText);
1201 } else {
1202 StringBuilder newText = new StringBuilder();
1203 newText.append(oldText).append(' ').append(switchText);
1204 info.setText(newText);
1205 }
1206 }
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -08001207 }
Alan Viverettecc2688d2013-09-17 17:00:12 -07001208
1209 private static final FloatProperty<Switch> THUMB_POS = new FloatProperty<Switch>("thumbPos") {
1210 @Override
1211 public Float get(Switch object) {
1212 return object.mThumbPosition;
1213 }
1214
1215 @Override
1216 public void setValue(Switch object, float value) {
1217 object.setThumbPosition(value);
1218 }
1219 };
Adam Powell12190b32010-11-28 19:07:53 -08001220}