blob: 4c8aa519108c4be401b3688d8c16fd56989f00e4 [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
Svetoslav Ganov63bce032011-07-23 19:52:17 -0700668 @Override
669 public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
670 super.onPopulateAccessibilityEvent(event);
Alan Viverette2a37cf8d2014-06-19 17:09:10 -0700671
672 final CharSequence text = isChecked() ? mTextOn : mTextOff;
673 if (text != null) {
674 event.getText().add(text);
Svetoslav Ganov76502592011-07-29 10:44:59 -0700675 }
Svetoslav Ganov63bce032011-07-23 19:52:17 -0700676 }
677
Adam Powell12190b32010-11-28 19:07:53 -0800678 private Layout makeLayout(CharSequence text) {
Daniel Sandler4c3308d2012-04-19 11:04:39 -0400679 final CharSequence transformed = (mSwitchTransformationMethod != null)
680 ? mSwitchTransformationMethod.getTransformation(text, this)
681 : text;
682
683 return new StaticLayout(transformed, mTextPaint,
684 (int) Math.ceil(Layout.getDesiredWidth(transformed, mTextPaint)),
Adam Powell12190b32010-11-28 19:07:53 -0800685 Layout.Alignment.ALIGN_NORMAL, 1.f, 0, true);
686 }
687
688 /**
689 * @return true if (x, y) is within the target area of the switch thumb
690 */
691 private boolean hitThumb(float x, float y) {
Alan Viverettecc2688d2013-09-17 17:00:12 -0700692 // Relies on mTempRect, MUST be called first!
693 final int thumbOffset = getThumbOffset();
694
Adam Powell12190b32010-11-28 19:07:53 -0800695 mThumbDrawable.getPadding(mTempRect);
696 final int thumbTop = mSwitchTop - mTouchSlop;
Alan Viverettecc2688d2013-09-17 17:00:12 -0700697 final int thumbLeft = mSwitchLeft + thumbOffset - mTouchSlop;
Adam Powell12190b32010-11-28 19:07:53 -0800698 final int thumbRight = thumbLeft + mThumbWidth +
699 mTempRect.left + mTempRect.right + mTouchSlop;
700 final int thumbBottom = mSwitchBottom + mTouchSlop;
701 return x > thumbLeft && x < thumbRight && y > thumbTop && y < thumbBottom;
702 }
703
704 @Override
705 public boolean onTouchEvent(MotionEvent ev) {
706 mVelocityTracker.addMovement(ev);
707 final int action = ev.getActionMasked();
708 switch (action) {
709 case MotionEvent.ACTION_DOWN: {
710 final float x = ev.getX();
711 final float y = ev.getY();
Gilles Debunnec2ab0d62011-06-13 12:52:48 -0700712 if (isEnabled() && hitThumb(x, y)) {
Adam Powell12190b32010-11-28 19:07:53 -0800713 mTouchMode = TOUCH_MODE_DOWN;
714 mTouchX = x;
715 mTouchY = y;
716 }
717 break;
718 }
719
720 case MotionEvent.ACTION_MOVE: {
721 switch (mTouchMode) {
722 case TOUCH_MODE_IDLE:
723 // Didn't target the thumb, treat normally.
724 break;
725
726 case TOUCH_MODE_DOWN: {
727 final float x = ev.getX();
728 final float y = ev.getY();
729 if (Math.abs(x - mTouchX) > mTouchSlop ||
730 Math.abs(y - mTouchY) > mTouchSlop) {
731 mTouchMode = TOUCH_MODE_DRAGGING;
732 getParent().requestDisallowInterceptTouchEvent(true);
733 mTouchX = x;
734 mTouchY = y;
735 return true;
736 }
737 break;
738 }
739
740 case TOUCH_MODE_DRAGGING: {
741 final float x = ev.getX();
Alan Viverettecc2688d2013-09-17 17:00:12 -0700742 final int thumbScrollRange = getThumbScrollRange();
743 final float thumbScrollOffset = x - mTouchX;
744 float dPos;
745 if (thumbScrollRange != 0) {
746 dPos = thumbScrollOffset / thumbScrollRange;
747 } else {
748 // If the thumb scroll range is empty, just use the
749 // movement direction to snap on or off.
750 dPos = thumbScrollOffset > 0 ? 1 : -1;
751 }
752 if (isLayoutRtl()) {
753 dPos = -dPos;
754 }
755 final float newPos = MathUtils.constrain(mThumbPosition + dPos, 0, 1);
Adam Powell12190b32010-11-28 19:07:53 -0800756 if (newPos != mThumbPosition) {
Adam Powell12190b32010-11-28 19:07:53 -0800757 mTouchX = x;
Alan Viverettecc2688d2013-09-17 17:00:12 -0700758 setThumbPosition(newPos);
Adam Powell12190b32010-11-28 19:07:53 -0800759 }
760 return true;
761 }
762 }
763 break;
764 }
765
766 case MotionEvent.ACTION_UP:
767 case MotionEvent.ACTION_CANCEL: {
768 if (mTouchMode == TOUCH_MODE_DRAGGING) {
769 stopDrag(ev);
Alan Viverettead2f8e32014-05-16 13:28:33 -0700770 // Allow super class to handle pressed state, etc.
771 super.onTouchEvent(ev);
Adam Powell12190b32010-11-28 19:07:53 -0800772 return true;
773 }
774 mTouchMode = TOUCH_MODE_IDLE;
775 mVelocityTracker.clear();
776 break;
777 }
778 }
779
780 return super.onTouchEvent(ev);
781 }
782
783 private void cancelSuperTouch(MotionEvent ev) {
784 MotionEvent cancel = MotionEvent.obtain(ev);
785 cancel.setAction(MotionEvent.ACTION_CANCEL);
786 super.onTouchEvent(cancel);
787 cancel.recycle();
788 }
789
790 /**
791 * Called from onTouchEvent to end a drag operation.
792 *
793 * @param ev Event that triggered the end of drag mode - ACTION_UP or ACTION_CANCEL
794 */
795 private void stopDrag(MotionEvent ev) {
796 mTouchMode = TOUCH_MODE_IDLE;
Adam Powell12190b32010-11-28 19:07:53 -0800797
Alan Viverette86453ff2013-09-26 14:46:08 -0700798 // Commit the change if the event is up and not canceled and the switch
799 // has not been disabled during the drag.
800 final boolean commitChange = ev.getAction() == MotionEvent.ACTION_UP && isEnabled();
Alan Viveretted4e77902014-10-27 17:50:51 -0700801 final boolean oldState = isChecked();
Alan Viverette86453ff2013-09-26 14:46:08 -0700802 final boolean newState;
Adam Powell12190b32010-11-28 19:07:53 -0800803 if (commitChange) {
Adam Powell12190b32010-11-28 19:07:53 -0800804 mVelocityTracker.computeCurrentVelocity(1000);
Alan Viverette86453ff2013-09-26 14:46:08 -0700805 final float xvel = mVelocityTracker.getXVelocity();
Adam Powell12190b32010-11-28 19:07:53 -0800806 if (Math.abs(xvel) > mMinFlingVelocity) {
Fabrice Di Meglio28efba32012-06-01 16:52:31 -0700807 newState = isLayoutRtl() ? (xvel < 0) : (xvel > 0);
Adam Powell12190b32010-11-28 19:07:53 -0800808 } else {
809 newState = getTargetCheckedState();
810 }
Adam Powell12190b32010-11-28 19:07:53 -0800811 } else {
Alan Viveretted4e77902014-10-27 17:50:51 -0700812 newState = oldState;
Adam Powell12190b32010-11-28 19:07:53 -0800813 }
Alan Viverette86453ff2013-09-26 14:46:08 -0700814
Alan Viveretted4e77902014-10-27 17:50:51 -0700815 if (newState != oldState) {
816 playSoundEffect(SoundEffectConstants.CLICK);
817 setChecked(newState);
818 }
819
Alan Viverette86453ff2013-09-26 14:46:08 -0700820 cancelSuperTouch(ev);
Adam Powell12190b32010-11-28 19:07:53 -0800821 }
822
823 private void animateThumbToCheckedState(boolean newCheckedState) {
Alan Viverettecc2688d2013-09-17 17:00:12 -0700824 final float targetPosition = newCheckedState ? 1 : 0;
825 mPositionAnimator = ObjectAnimator.ofFloat(this, THUMB_POS, targetPosition);
826 mPositionAnimator.setDuration(THUMB_ANIMATION_DURATION);
827 mPositionAnimator.setAutoCancel(true);
828 mPositionAnimator.start();
829 }
830
831 private void cancelPositionAnimator() {
832 if (mPositionAnimator != null) {
833 mPositionAnimator.cancel();
834 }
Adam Powell12190b32010-11-28 19:07:53 -0800835 }
836
837 private boolean getTargetCheckedState() {
Alan Viverettecc2688d2013-09-17 17:00:12 -0700838 return mThumbPosition > 0.5f;
Fabrice Di Meglio28efba32012-06-01 16:52:31 -0700839 }
840
Alan Viverettecc2688d2013-09-17 17:00:12 -0700841 /**
842 * Sets the thumb position as a decimal value between 0 (off) and 1 (on).
843 *
844 * @param position new position between [0,1]
845 */
846 private void setThumbPosition(float position) {
847 mThumbPosition = position;
848 invalidate();
849 }
850
851 @Override
852 public void toggle() {
Alan Viverette86453ff2013-09-26 14:46:08 -0700853 setChecked(!isChecked());
Adam Powell12190b32010-11-28 19:07:53 -0800854 }
855
856 @Override
857 public void setChecked(boolean checked) {
858 super.setChecked(checked);
Alan Viverettecc2688d2013-09-17 17:00:12 -0700859
Alan Viverette467d6292014-08-12 15:13:19 -0700860 // Calling the super method may result in setChecked() getting called
861 // recursively with a different value, so load the REAL value...
862 checked = isChecked();
863
Alan Viverette86453ff2013-09-26 14:46:08 -0700864 if (isAttachedToWindow() && isLaidOut()) {
865 animateThumbToCheckedState(checked);
866 } else {
867 // Immediately move the thumb to the new position.
868 cancelPositionAnimator();
869 setThumbPosition(checked ? 1 : 0);
870 }
Adam Powell12190b32010-11-28 19:07:53 -0800871 }
872
873 @Override
874 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
875 super.onLayout(changed, left, top, right, bottom);
876
Alan Viverette0c0dde72014-07-30 13:29:39 -0700877 int opticalInsetLeft = 0;
878 int opticalInsetRight = 0;
879 if (mThumbDrawable != null) {
880 final Rect trackPadding = mTempRect;
881 if (mTrackDrawable != null) {
882 mTrackDrawable.getPadding(trackPadding);
883 } else {
884 trackPadding.setEmpty();
885 }
Fabrice Di Meglio28efba32012-06-01 16:52:31 -0700886
Alan Viverette0c0dde72014-07-30 13:29:39 -0700887 final Insets insets = mThumbDrawable.getOpticalInsets();
888 opticalInsetLeft = Math.max(0, insets.left - trackPadding.left);
889 opticalInsetRight = Math.max(0, insets.right - trackPadding.right);
Alan Viverette8bb39902014-07-29 17:22:30 -0700890 }
891
Alan Viverette0c0dde72014-07-30 13:29:39 -0700892 final int switchRight;
893 final int switchLeft;
894 if (isLayoutRtl()) {
895 switchLeft = getPaddingLeft() + opticalInsetLeft;
896 switchRight = switchLeft + mSwitchWidth - opticalInsetLeft - opticalInsetRight;
897 } else {
898 switchRight = getWidth() - getPaddingRight() - opticalInsetRight;
899 switchLeft = switchRight - mSwitchWidth + opticalInsetLeft + opticalInsetRight;
900 }
901
902 final int switchTop;
903 final int switchBottom;
Adam Powell12190b32010-11-28 19:07:53 -0800904 switch (getGravity() & Gravity.VERTICAL_GRAVITY_MASK) {
905 default:
906 case Gravity.TOP:
907 switchTop = getPaddingTop();
908 switchBottom = switchTop + mSwitchHeight;
909 break;
910
911 case Gravity.CENTER_VERTICAL:
912 switchTop = (getPaddingTop() + getHeight() - getPaddingBottom()) / 2 -
913 mSwitchHeight / 2;
914 switchBottom = switchTop + mSwitchHeight;
915 break;
916
917 case Gravity.BOTTOM:
918 switchBottom = getHeight() - getPaddingBottom();
919 switchTop = switchBottom - mSwitchHeight;
920 break;
921 }
922
923 mSwitchLeft = switchLeft;
924 mSwitchTop = switchTop;
925 mSwitchBottom = switchBottom;
926 mSwitchRight = switchRight;
927 }
928
929 @Override
Alan Viverettead2f8e32014-05-16 13:28:33 -0700930 public void draw(Canvas c) {
Alan Viverette4d065a02014-07-11 15:28:38 -0700931 final Rect padding = mTempRect;
Alan Viverette5876ff42014-03-03 17:40:46 -0800932 final int switchLeft = mSwitchLeft;
933 final int switchTop = mSwitchTop;
934 final int switchRight = mSwitchRight;
935 final int switchBottom = mSwitchBottom;
Alan Viverette0c0dde72014-07-30 13:29:39 -0700936
937 int thumbInitialLeft = switchLeft + getThumbOffset();
938
939 final Insets thumbInsets;
940 if (mThumbDrawable != null) {
941 thumbInsets = mThumbDrawable.getOpticalInsets();
942 } else {
943 thumbInsets = Insets.NONE;
Alan Viverette8bb39902014-07-29 17:22:30 -0700944 }
Alan Viverettecc2688d2013-09-17 17:00:12 -0700945
Alan Viverette0c0dde72014-07-30 13:29:39 -0700946 // Layout the track.
947 if (mTrackDrawable != null) {
948 mTrackDrawable.getPadding(padding);
Alan Viverette9b38f6c2014-07-30 02:39:07 +0000949
Alan Viverette0c0dde72014-07-30 13:29:39 -0700950 // Adjust thumb position for track padding.
951 thumbInitialLeft += padding.left;
952
953 // If necessary, offset by the optical insets of the thumb asset.
954 int trackLeft = switchLeft;
955 int trackTop = switchTop;
956 int trackRight = switchRight;
957 int trackBottom = switchBottom;
958 if (thumbInsets != Insets.NONE) {
959 if (thumbInsets.left > padding.left) {
960 trackLeft += thumbInsets.left - padding.left;
961 }
962 if (thumbInsets.top > padding.top) {
963 trackTop += thumbInsets.top - padding.top;
964 }
965 if (thumbInsets.right > padding.right) {
966 trackRight -= thumbInsets.right - padding.right;
967 }
968 if (thumbInsets.bottom > padding.bottom) {
969 trackBottom -= thumbInsets.bottom - padding.bottom;
970 }
971 }
972 mTrackDrawable.setBounds(trackLeft, trackTop, trackRight, trackBottom);
973 }
Alan Viverette9b38f6c2014-07-30 02:39:07 +0000974
Alan Viverette661e6362014-05-12 10:55:37 -0700975 // Layout the thumb.
Alan Viverette4d065a02014-07-11 15:28:38 -0700976 if (mThumbDrawable != null) {
977 mThumbDrawable.getPadding(padding);
Alan Viverette0c0dde72014-07-30 13:29:39 -0700978
979 final int thumbLeft = thumbInitialLeft - padding.left;
980 final int thumbRight = thumbInitialLeft + mThumbWidth + padding.right;
Alan Viverette4d065a02014-07-11 15:28:38 -0700981 mThumbDrawable.setBounds(thumbLeft, switchTop, thumbRight, switchBottom);
Alan Viverette61956602014-04-22 19:07:06 -0700982
Alan Viverette4d065a02014-07-11 15:28:38 -0700983 final Drawable background = getBackground();
984 if (background != null) {
985 background.setHotspotBounds(thumbLeft, switchTop, thumbRight, switchBottom);
986 }
Alan Viverette61956602014-04-22 19:07:06 -0700987 }
988
Alan Viverettead2f8e32014-05-16 13:28:33 -0700989 // Draw the background.
990 super.draw(c);
991 }
992
993 @Override
994 protected void onDraw(Canvas canvas) {
Alan Viverette61956602014-04-22 19:07:06 -0700995 super.onDraw(canvas);
996
Alan Viverette4d065a02014-07-11 15:28:38 -0700997 final Rect padding = mTempRect;
Alan Viverettead2f8e32014-05-16 13:28:33 -0700998 final Drawable trackDrawable = mTrackDrawable;
Alan Viverette4d065a02014-07-11 15:28:38 -0700999 if (trackDrawable != null) {
1000 trackDrawable.getPadding(padding);
1001 } else {
1002 padding.setEmpty();
1003 }
Alan Viverettead2f8e32014-05-16 13:28:33 -07001004
1005 final int switchTop = mSwitchTop;
1006 final int switchBottom = mSwitchBottom;
Alan Viverette4d065a02014-07-11 15:28:38 -07001007 final int switchInnerTop = switchTop + padding.top;
Alan Viverette4d065a02014-07-11 15:28:38 -07001008 final int switchInnerBottom = switchBottom - padding.bottom;
Alan Viverettead2f8e32014-05-16 13:28:33 -07001009
Alan Viverette4d065a02014-07-11 15:28:38 -07001010 final Drawable thumbDrawable = mThumbDrawable;
1011 if (trackDrawable != null) {
1012 if (mSplitTrack && thumbDrawable != null) {
1013 final Insets insets = thumbDrawable.getOpticalInsets();
1014 thumbDrawable.copyBounds(padding);
1015 padding.left += insets.left;
1016 padding.right -= insets.right;
Alan Viverette661e6362014-05-12 10:55:37 -07001017
Alan Viverette4d065a02014-07-11 15:28:38 -07001018 final int saveCount = canvas.save();
1019 canvas.clipRect(padding, Op.DIFFERENCE);
1020 trackDrawable.draw(canvas);
1021 canvas.restoreToCount(saveCount);
1022 } else {
1023 trackDrawable.draw(canvas);
1024 }
Alan Viverette661e6362014-05-12 10:55:37 -07001025 }
Alan Viverette61956602014-04-22 19:07:06 -07001026
1027 final int saveCount = canvas.save();
Alan Viverette4d065a02014-07-11 15:28:38 -07001028
1029 if (thumbDrawable != null) {
Alan Viverette4d065a02014-07-11 15:28:38 -07001030 thumbDrawable.draw(canvas);
1031 }
Adam Powell12190b32010-11-28 19:07:53 -08001032
Alan Viverette5876ff42014-03-03 17:40:46 -08001033 final Layout switchText = getTargetCheckedState() ? mOnLayout : mOffLayout;
Fabrice Di Megliobe06e322012-09-11 17:42:45 -07001034 if (switchText != null) {
Alan Viverette661e6362014-05-12 10:55:37 -07001035 final int drawableState[] = getDrawableState();
1036 if (mTextColors != null) {
1037 mTextPaint.setColor(mTextColors.getColorForState(drawableState, 0));
1038 }
1039 mTextPaint.drawableState = drawableState;
1040
Alan Viverette4d065a02014-07-11 15:28:38 -07001041 final int cX;
1042 if (thumbDrawable != null) {
1043 final Rect bounds = thumbDrawable.getBounds();
1044 cX = bounds.left + bounds.right;
1045 } else {
Alan Viverettedec17292014-07-12 00:26:36 -07001046 cX = getWidth();
Alan Viverette4d065a02014-07-11 15:28:38 -07001047 }
1048
1049 final int left = cX / 2 - switchText.getWidth() / 2;
Alan Viverette5876ff42014-03-03 17:40:46 -08001050 final int top = (switchInnerTop + switchInnerBottom) / 2 - switchText.getHeight() / 2;
1051 canvas.translate(left, top);
Fabrice Di Megliobe06e322012-09-11 17:42:45 -07001052 switchText.draw(canvas);
1053 }
Adam Powell12190b32010-11-28 19:07:53 -08001054
Alan Viverette5876ff42014-03-03 17:40:46 -08001055 canvas.restoreToCount(saveCount);
Adam Powell12190b32010-11-28 19:07:53 -08001056 }
1057
1058 @Override
Fabrice Di Meglio28efba32012-06-01 16:52:31 -07001059 public int getCompoundPaddingLeft() {
1060 if (!isLayoutRtl()) {
1061 return super.getCompoundPaddingLeft();
1062 }
1063 int padding = super.getCompoundPaddingLeft() + mSwitchWidth;
1064 if (!TextUtils.isEmpty(getText())) {
1065 padding += mSwitchPadding;
1066 }
1067 return padding;
1068 }
1069
1070 @Override
Adam Powell12190b32010-11-28 19:07:53 -08001071 public int getCompoundPaddingRight() {
Fabrice Di Meglio28efba32012-06-01 16:52:31 -07001072 if (isLayoutRtl()) {
1073 return super.getCompoundPaddingRight();
1074 }
Adam Powell12190b32010-11-28 19:07:53 -08001075 int padding = super.getCompoundPaddingRight() + mSwitchWidth;
1076 if (!TextUtils.isEmpty(getText())) {
1077 padding += mSwitchPadding;
1078 }
1079 return padding;
1080 }
1081
Alan Viverettecc2688d2013-09-17 17:00:12 -07001082 /**
1083 * Translates thumb position to offset according to current RTL setting and
Alan Viverette0c0dde72014-07-30 13:29:39 -07001084 * thumb scroll range. Accounts for both track and thumb padding.
Alan Viverettecc2688d2013-09-17 17:00:12 -07001085 *
1086 * @return thumb offset
1087 */
1088 private int getThumbOffset() {
1089 final float thumbPosition;
1090 if (isLayoutRtl()) {
1091 thumbPosition = 1 - mThumbPosition;
1092 } else {
1093 thumbPosition = mThumbPosition;
1094 }
1095 return (int) (thumbPosition * getThumbScrollRange() + 0.5f);
1096 }
1097
Adam Powell12190b32010-11-28 19:07:53 -08001098 private int getThumbScrollRange() {
Alan Viverette4d065a02014-07-11 15:28:38 -07001099 if (mTrackDrawable != null) {
Alan Viverette0c0dde72014-07-30 13:29:39 -07001100 final Rect padding = mTempRect;
1101 mTrackDrawable.getPadding(padding);
1102
1103 final Insets insets;
1104 if (mThumbDrawable != null) {
1105 insets = mThumbDrawable.getOpticalInsets();
1106 } else {
1107 insets = Insets.NONE;
1108 }
1109
1110 return mSwitchWidth - mThumbWidth - padding.left - padding.right
1111 - insets.left - insets.right;
Alan Viverette4d065a02014-07-11 15:28:38 -07001112 } else {
Adam Powell12190b32010-11-28 19:07:53 -08001113 return 0;
1114 }
Adam Powell12190b32010-11-28 19:07:53 -08001115 }
1116
1117 @Override
1118 protected int[] onCreateDrawableState(int extraSpace) {
1119 final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
1120 if (isChecked()) {
1121 mergeDrawableStates(drawableState, CHECKED_STATE_SET);
1122 }
1123 return drawableState;
1124 }
1125
1126 @Override
1127 protected void drawableStateChanged() {
1128 super.drawableStateChanged();
1129
Alan Viverette661e6362014-05-12 10:55:37 -07001130 final int[] myDrawableState = getDrawableState();
Adam Powell12190b32010-11-28 19:07:53 -08001131
Alan Viverette2356c5e2014-05-22 22:43:59 -07001132 if (mThumbDrawable != null) {
1133 mThumbDrawable.setState(myDrawableState);
Alan Viverette661e6362014-05-12 10:55:37 -07001134 }
1135
1136 if (mTrackDrawable != null) {
1137 mTrackDrawable.setState(myDrawableState);
1138 }
Adam Powell12190b32010-11-28 19:07:53 -08001139
1140 invalidate();
1141 }
1142
Alan Viverettecebc6ba2014-06-13 15:52:13 -07001143 @Override
Alan Viverette8de14942014-06-18 18:05:15 -07001144 public void drawableHotspotChanged(float x, float y) {
1145 super.drawableHotspotChanged(x, y);
Alan Viverettecebc6ba2014-06-13 15:52:13 -07001146
1147 if (mThumbDrawable != null) {
1148 mThumbDrawable.setHotspot(x, y);
1149 }
1150
1151 if (mTrackDrawable != null) {
1152 mTrackDrawable.setHotspot(x, y);
1153 }
1154 }
1155
Adam Powell12190b32010-11-28 19:07:53 -08001156 @Override
1157 protected boolean verifyDrawable(Drawable who) {
1158 return super.verifyDrawable(who) || who == mThumbDrawable || who == mTrackDrawable;
1159 }
1160
1161 @Override
1162 public void jumpDrawablesToCurrentState() {
1163 super.jumpDrawablesToCurrentState();
Alan Viverette4d065a02014-07-11 15:28:38 -07001164
1165 if (mThumbDrawable != null) {
1166 mThumbDrawable.jumpToCurrentState();
1167 }
1168
1169 if (mTrackDrawable != null) {
1170 mTrackDrawable.jumpToCurrentState();
1171 }
1172
1173 if (mPositionAnimator != null && mPositionAnimator.isRunning()) {
1174 mPositionAnimator.end();
1175 mPositionAnimator = null;
1176 }
Adam Powell12190b32010-11-28 19:07:53 -08001177 }
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -08001178
1179 @Override
1180 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
1181 super.onInitializeAccessibilityEvent(event);
1182 event.setClassName(Switch.class.getName());
1183 }
1184
1185 @Override
1186 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
1187 super.onInitializeAccessibilityNodeInfo(info);
1188 info.setClassName(Switch.class.getName());
Svetoslav Ganov78bcc152012-04-12 17:17:19 -07001189 CharSequence switchText = isChecked() ? mTextOn : mTextOff;
1190 if (!TextUtils.isEmpty(switchText)) {
1191 CharSequence oldText = info.getText();
1192 if (TextUtils.isEmpty(oldText)) {
1193 info.setText(switchText);
1194 } else {
1195 StringBuilder newText = new StringBuilder();
1196 newText.append(oldText).append(' ').append(switchText);
1197 info.setText(newText);
1198 }
1199 }
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -08001200 }
Alan Viverettecc2688d2013-09-17 17:00:12 -07001201
1202 private static final FloatProperty<Switch> THUMB_POS = new FloatProperty<Switch>("thumbPos") {
1203 @Override
1204 public Float get(Switch object) {
1205 return object.mThumbPosition;
1206 }
1207
1208 @Override
1209 public void setValue(Switch object, float value) {
1210 object.setThumbPosition(value);
1211 }
1212 };
Adam Powell12190b32010-11-28 19:07:53 -08001213}