blob: 8b97329646b47a09538d91c301ebdae780458ede [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;
42import android.view.VelocityTracker;
43import android.view.ViewConfiguration;
Svetoslav Ganov63bce032011-07-23 19:52:17 -070044import android.view.accessibility.AccessibilityEvent;
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -080045import android.view.accessibility.AccessibilityNodeInfo;
Adam Powell12190b32010-11-28 19:07:53 -080046
Adam Powellbe0a4532010-11-29 17:47:48 -080047import com.android.internal.R;
48
Adam Powell12190b32010-11-28 19:07:53 -080049/**
50 * A Switch is a two-state toggle switch widget that can select between two
51 * options. The user may drag the "thumb" back and forth to choose the selected option,
Chet Haase150176d2011-08-26 09:54:06 -070052 * or simply tap to toggle as if it were a checkbox. The {@link #setText(CharSequence) text}
53 * property controls the text displayed in the label for the switch, whereas the
54 * {@link #setTextOff(CharSequence) off} and {@link #setTextOn(CharSequence) on} text
55 * controls the text on the thumb. Similarly, the
56 * {@link #setTextAppearance(android.content.Context, int) textAppearance} and the related
57 * setTypeface() methods control the typeface and style of label text, whereas the
58 * {@link #setSwitchTextAppearance(android.content.Context, int) switchTextAppearance} and
59 * the related seSwitchTypeface() methods control that of the thumb.
Adam Powell12190b32010-11-28 19:07:53 -080060 *
Scott Main4c359b72012-07-24 15:51:27 -070061 * <p>See the <a href="{@docRoot}guide/topics/ui/controls/togglebutton.html">Toggle Buttons</a>
62 * guide.</p>
63 *
64 * @attr ref android.R.styleable#Switch_textOn
65 * @attr ref android.R.styleable#Switch_textOff
66 * @attr ref android.R.styleable#Switch_switchMinWidth
67 * @attr ref android.R.styleable#Switch_switchPadding
68 * @attr ref android.R.styleable#Switch_switchTextAppearance
69 * @attr ref android.R.styleable#Switch_thumb
70 * @attr ref android.R.styleable#Switch_thumbTextPadding
71 * @attr ref android.R.styleable#Switch_track
Adam Powell12190b32010-11-28 19:07:53 -080072 */
73public class Switch extends CompoundButton {
Alan Viverettecc2688d2013-09-17 17:00:12 -070074 private static final int THUMB_ANIMATION_DURATION = 250;
75
Adam Powell12190b32010-11-28 19:07:53 -080076 private static final int TOUCH_MODE_IDLE = 0;
77 private static final int TOUCH_MODE_DOWN = 1;
78 private static final int TOUCH_MODE_DRAGGING = 2;
79
80 // Enum for the "typeface" XML parameter.
81 private static final int SANS = 1;
82 private static final int SERIF = 2;
83 private static final int MONOSPACE = 3;
84
85 private Drawable mThumbDrawable;
86 private Drawable mTrackDrawable;
87 private int mThumbTextPadding;
88 private int mSwitchMinWidth;
89 private int mSwitchPadding;
Alan Viverette661e6362014-05-12 10:55:37 -070090 private boolean mSplitTrack;
Adam Powell12190b32010-11-28 19:07:53 -080091 private CharSequence mTextOn;
92 private CharSequence mTextOff;
Alan Viverette2a37cf8d2014-06-19 17:09:10 -070093 private boolean mShowText;
Adam Powell12190b32010-11-28 19:07:53 -080094
95 private int mTouchMode;
96 private int mTouchSlop;
97 private float mTouchX;
98 private float mTouchY;
99 private VelocityTracker mVelocityTracker = VelocityTracker.obtain();
100 private int mMinFlingVelocity;
101
102 private float mThumbPosition;
Alan Viverette8bb39902014-07-29 17:22:30 -0700103
Alan Viverette0c0dde72014-07-30 13:29:39 -0700104 /**
105 * Width required to draw the switch track and thumb. Includes padding and
106 * optical bounds for both the track and thumb.
107 */
108 private int mSwitchWidth;
109
110 /**
111 * Height required to draw the switch track and thumb. Includes padding and
112 * optical bounds for both the track and thumb.
113 */
114 private int mSwitchHeight;
115
116 /**
117 * Width of the thumb's content region. Does not include padding or
118 * optical bounds.
119 */
120 private int mThumbWidth;
121
122 /** Left bound for drawing the switch track and thumb. */
Adam Powell12190b32010-11-28 19:07:53 -0800123 private int mSwitchLeft;
Alan Viverette0c0dde72014-07-30 13:29:39 -0700124
125 /** Top bound for drawing the switch track and thumb. */
Adam Powell12190b32010-11-28 19:07:53 -0800126 private int mSwitchTop;
Alan Viverette0c0dde72014-07-30 13:29:39 -0700127
128 /** Right bound for drawing the switch track and thumb. */
Adam Powell12190b32010-11-28 19:07:53 -0800129 private int mSwitchRight;
Alan Viverette0c0dde72014-07-30 13:29:39 -0700130
131 /** Bottom bound for drawing the switch track and thumb. */
Adam Powell12190b32010-11-28 19:07:53 -0800132 private int mSwitchBottom;
133
134 private TextPaint mTextPaint;
135 private ColorStateList mTextColors;
136 private Layout mOnLayout;
137 private Layout mOffLayout;
Daniel Sandler4c3308d2012-04-19 11:04:39 -0400138 private TransformationMethod2 mSwitchTransformationMethod;
Alan Viverettecc2688d2013-09-17 17:00:12 -0700139 private ObjectAnimator mPositionAnimator;
Adam Powell12190b32010-11-28 19:07:53 -0800140
Adam Powellbe0a4532010-11-29 17:47:48 -0800141 @SuppressWarnings("hiding")
Adam Powell12190b32010-11-28 19:07:53 -0800142 private final Rect mTempRect = new Rect();
143
144 private static final int[] CHECKED_STATE_SET = {
145 R.attr.state_checked
146 };
147
148 /**
149 * Construct a new Switch with default styling.
150 *
151 * @param context The Context that will determine this widget's theming.
152 */
153 public Switch(Context context) {
154 this(context, null);
155 }
156
157 /**
158 * Construct a new Switch with default styling, overriding specific style
159 * attributes as requested.
160 *
161 * @param context The Context that will determine this widget's theming.
162 * @param attrs Specification of attributes that should deviate from default styling.
163 */
164 public Switch(Context context, AttributeSet attrs) {
165 this(context, attrs, com.android.internal.R.attr.switchStyle);
166 }
167
168 /**
169 * Construct a new Switch with a default style determined by the given theme attribute,
170 * overriding specific style attributes as requested.
171 *
172 * @param context The Context that will determine this widget's theming.
173 * @param attrs Specification of attributes that should deviate from the default styling.
Alan Viverette617feb92013-09-09 18:09:13 -0700174 * @param defStyleAttr An attribute in the current theme that contains a
175 * reference to a style resource that supplies default values for
176 * the view. Can be 0 to not look for defaults.
Adam Powell12190b32010-11-28 19:07:53 -0800177 */
Alan Viverette617feb92013-09-09 18:09:13 -0700178 public Switch(Context context, AttributeSet attrs, int defStyleAttr) {
179 this(context, attrs, defStyleAttr, 0);
180 }
181
182
183 /**
184 * Construct a new Switch with a default style determined by the given theme
185 * attribute or style resource, overriding specific style attributes as
186 * requested.
187 *
188 * @param context The Context that will determine this widget's theming.
189 * @param attrs Specification of attributes that should deviate from the
190 * default styling.
191 * @param defStyleAttr An attribute in the current theme that contains a
192 * reference to a style resource that supplies default values for
193 * the view. Can be 0 to not look for defaults.
194 * @param defStyleRes A resource identifier of a style resource that
195 * supplies default values for the view, used only if
196 * defStyleAttr is 0 or can not be found in the theme. Can be 0
197 * to not look for defaults.
198 */
199 public Switch(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
200 super(context, attrs, defStyleAttr, defStyleRes);
Adam Powell12190b32010-11-28 19:07:53 -0800201
202 mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
Alan Viverette661e6362014-05-12 10:55:37 -0700203
204 final Resources res = getResources();
Adam Powell12190b32010-11-28 19:07:53 -0800205 mTextPaint.density = res.getDisplayMetrics().density;
206 mTextPaint.setCompatibilityScaling(res.getCompatibilityInfo().applicationScale);
207
Alan Viverette617feb92013-09-09 18:09:13 -0700208 final TypedArray a = context.obtainStyledAttributes(
209 attrs, com.android.internal.R.styleable.Switch, defStyleAttr, defStyleRes);
Chet Haase150176d2011-08-26 09:54:06 -0700210 mThumbDrawable = a.getDrawable(com.android.internal.R.styleable.Switch_thumb);
211 mTrackDrawable = a.getDrawable(com.android.internal.R.styleable.Switch_track);
Adam Powell12190b32010-11-28 19:07:53 -0800212 mTextOn = a.getText(com.android.internal.R.styleable.Switch_textOn);
213 mTextOff = a.getText(com.android.internal.R.styleable.Switch_textOff);
Alan Viverette2a37cf8d2014-06-19 17:09:10 -0700214 mShowText = a.getBoolean(com.android.internal.R.styleable.Switch_showText, true);
Adam Powell12190b32010-11-28 19:07:53 -0800215 mThumbTextPadding = a.getDimensionPixelSize(
216 com.android.internal.R.styleable.Switch_thumbTextPadding, 0);
217 mSwitchMinWidth = a.getDimensionPixelSize(
218 com.android.internal.R.styleable.Switch_switchMinWidth, 0);
219 mSwitchPadding = a.getDimensionPixelSize(
220 com.android.internal.R.styleable.Switch_switchPadding, 0);
Alan Viverette661e6362014-05-12 10:55:37 -0700221 mSplitTrack = a.getBoolean(com.android.internal.R.styleable.Switch_splitTrack, false);
Adam Powell12190b32010-11-28 19:07:53 -0800222
Alan Viverette661e6362014-05-12 10:55:37 -0700223 final int appearance = a.getResourceId(
Adam Powell12190b32010-11-28 19:07:53 -0800224 com.android.internal.R.styleable.Switch_switchTextAppearance, 0);
225 if (appearance != 0) {
Chet Haase150176d2011-08-26 09:54:06 -0700226 setSwitchTextAppearance(context, appearance);
Adam Powell12190b32010-11-28 19:07:53 -0800227 }
228 a.recycle();
229
Alan Viverette661e6362014-05-12 10:55:37 -0700230 final ViewConfiguration config = ViewConfiguration.get(context);
Adam Powell12190b32010-11-28 19:07:53 -0800231 mTouchSlop = config.getScaledTouchSlop();
232 mMinFlingVelocity = config.getScaledMinimumFlingVelocity();
233
234 // Refresh display with current params
Gilles Debunnee724ee42011-08-31 11:20:27 -0700235 refreshDrawableState();
Adam Powell12190b32010-11-28 19:07:53 -0800236 setChecked(isChecked());
237 }
238
239 /**
240 * Sets the switch text color, size, style, hint color, and highlight color
241 * from the specified TextAppearance resource.
Adam Powell6c86e1b2012-03-08 15:11:46 -0800242 *
243 * @attr ref android.R.styleable#Switch_switchTextAppearance
Adam Powell12190b32010-11-28 19:07:53 -0800244 */
Chet Haase150176d2011-08-26 09:54:06 -0700245 public void setSwitchTextAppearance(Context context, int resid) {
Adam Powell12190b32010-11-28 19:07:53 -0800246 TypedArray appearance =
Chet Haase150176d2011-08-26 09:54:06 -0700247 context.obtainStyledAttributes(resid,
Adam Powell12190b32010-11-28 19:07:53 -0800248 com.android.internal.R.styleable.TextAppearance);
249
250 ColorStateList colors;
251 int ts;
252
253 colors = appearance.getColorStateList(com.android.internal.R.styleable.
254 TextAppearance_textColor);
255 if (colors != null) {
256 mTextColors = colors;
Chet Haase150176d2011-08-26 09:54:06 -0700257 } else {
258 // If no color set in TextAppearance, default to the view's textColor
259 mTextColors = getTextColors();
Adam Powell12190b32010-11-28 19:07:53 -0800260 }
261
262 ts = appearance.getDimensionPixelSize(com.android.internal.R.styleable.
263 TextAppearance_textSize, 0);
264 if (ts != 0) {
265 if (ts != mTextPaint.getTextSize()) {
266 mTextPaint.setTextSize(ts);
267 requestLayout();
268 }
269 }
270
271 int typefaceIndex, styleIndex;
272
273 typefaceIndex = appearance.getInt(com.android.internal.R.styleable.
274 TextAppearance_typeface, -1);
275 styleIndex = appearance.getInt(com.android.internal.R.styleable.
276 TextAppearance_textStyle, -1);
277
278 setSwitchTypefaceByIndex(typefaceIndex, styleIndex);
279
Daniel Sandler4c3308d2012-04-19 11:04:39 -0400280 boolean allCaps = appearance.getBoolean(com.android.internal.R.styleable.
281 TextAppearance_textAllCaps, false);
282 if (allCaps) {
283 mSwitchTransformationMethod = new AllCapsTransformationMethod(getContext());
284 mSwitchTransformationMethod.setLengthChangesAllowed(true);
285 } else {
286 mSwitchTransformationMethod = null;
287 }
288
Adam Powell12190b32010-11-28 19:07:53 -0800289 appearance.recycle();
290 }
291
292 private void setSwitchTypefaceByIndex(int typefaceIndex, int styleIndex) {
293 Typeface tf = null;
294 switch (typefaceIndex) {
295 case SANS:
296 tf = Typeface.SANS_SERIF;
297 break;
298
299 case SERIF:
300 tf = Typeface.SERIF;
301 break;
302
303 case MONOSPACE:
304 tf = Typeface.MONOSPACE;
305 break;
306 }
307
308 setSwitchTypeface(tf, styleIndex);
309 }
310
311 /**
312 * Sets the typeface and style in which the text should be displayed on the
313 * switch, and turns on the fake bold and italic bits in the Paint if the
314 * Typeface that you provided does not have all the bits in the
315 * style that you specified.
316 */
317 public void setSwitchTypeface(Typeface tf, int style) {
318 if (style > 0) {
319 if (tf == null) {
320 tf = Typeface.defaultFromStyle(style);
321 } else {
322 tf = Typeface.create(tf, style);
323 }
324
325 setSwitchTypeface(tf);
326 // now compute what (if any) algorithmic styling is needed
327 int typefaceStyle = tf != null ? tf.getStyle() : 0;
328 int need = style & ~typefaceStyle;
329 mTextPaint.setFakeBoldText((need & Typeface.BOLD) != 0);
330 mTextPaint.setTextSkewX((need & Typeface.ITALIC) != 0 ? -0.25f : 0);
331 } else {
Victoria Leaseaa0980a2012-06-11 14:46:04 -0700332 mTextPaint.setFakeBoldText(false);
Adam Powell12190b32010-11-28 19:07:53 -0800333 mTextPaint.setTextSkewX(0);
334 setSwitchTypeface(tf);
335 }
336 }
337
338 /**
Chet Haase150176d2011-08-26 09:54:06 -0700339 * Sets the typeface in which the text should be displayed on the switch.
Adam Powell12190b32010-11-28 19:07:53 -0800340 * Note that not all Typeface families actually have bold and italic
341 * variants, so you may need to use
342 * {@link #setSwitchTypeface(Typeface, int)} to get the appearance
343 * that you actually want.
344 *
345 * @attr ref android.R.styleable#TextView_typeface
346 * @attr ref android.R.styleable#TextView_textStyle
347 */
348 public void setSwitchTypeface(Typeface tf) {
349 if (mTextPaint.getTypeface() != tf) {
350 mTextPaint.setTypeface(tf);
351
352 requestLayout();
353 invalidate();
354 }
355 }
356
357 /**
Adam Powell6c86e1b2012-03-08 15:11:46 -0800358 * Set the amount of horizontal padding between the switch and the associated text.
359 *
360 * @param pixels Amount of padding in pixels
361 *
362 * @attr ref android.R.styleable#Switch_switchPadding
363 */
364 public void setSwitchPadding(int pixels) {
365 mSwitchPadding = pixels;
366 requestLayout();
367 }
368
369 /**
370 * Get the amount of horizontal padding between the switch and the associated text.
371 *
372 * @return Amount of padding in pixels
373 *
374 * @attr ref android.R.styleable#Switch_switchPadding
375 */
376 public int getSwitchPadding() {
377 return mSwitchPadding;
378 }
379
380 /**
381 * Set the minimum width of the switch in pixels. The switch's width will be the maximum
382 * of this value and its measured width as determined by the switch drawables and text used.
383 *
384 * @param pixels Minimum width of the switch in pixels
385 *
386 * @attr ref android.R.styleable#Switch_switchMinWidth
387 */
388 public void setSwitchMinWidth(int pixels) {
389 mSwitchMinWidth = pixels;
390 requestLayout();
391 }
392
393 /**
394 * Get the minimum width of the switch in pixels. The switch's width will be the maximum
395 * of this value and its measured width as determined by the switch drawables and text used.
396 *
397 * @return Minimum width of the switch in pixels
398 *
399 * @attr ref android.R.styleable#Switch_switchMinWidth
400 */
401 public int getSwitchMinWidth() {
402 return mSwitchMinWidth;
403 }
404
405 /**
406 * Set the horizontal padding around the text drawn on the switch itself.
407 *
408 * @param pixels Horizontal padding for switch thumb text in pixels
409 *
410 * @attr ref android.R.styleable#Switch_thumbTextPadding
411 */
412 public void setThumbTextPadding(int pixels) {
413 mThumbTextPadding = pixels;
414 requestLayout();
415 }
416
417 /**
418 * Get the horizontal padding around the text drawn on the switch itself.
419 *
420 * @return Horizontal padding for switch thumb text in pixels
421 *
422 * @attr ref android.R.styleable#Switch_thumbTextPadding
423 */
424 public int getThumbTextPadding() {
425 return mThumbTextPadding;
426 }
427
428 /**
429 * Set the drawable used for the track that the switch slides within.
430 *
431 * @param track Track drawable
432 *
433 * @attr ref android.R.styleable#Switch_track
434 */
435 public void setTrackDrawable(Drawable track) {
436 mTrackDrawable = track;
437 requestLayout();
438 }
439
440 /**
Adam Powelld9c7be62012-03-08 19:43:43 -0800441 * Set the drawable used for the track that the switch slides within.
442 *
Adam Powelldca510e2012-03-08 20:06:39 -0800443 * @param resId Resource ID of a track drawable
Adam Powelld9c7be62012-03-08 19:43:43 -0800444 *
445 * @attr ref android.R.styleable#Switch_track
446 */
447 public void setTrackResource(int resId) {
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800448 setTrackDrawable(getContext().getDrawable(resId));
Adam Powelld9c7be62012-03-08 19:43:43 -0800449 }
450
451 /**
Adam Powell6c86e1b2012-03-08 15:11:46 -0800452 * Get the drawable used for the track that the switch slides within.
453 *
454 * @return Track drawable
455 *
456 * @attr ref android.R.styleable#Switch_track
457 */
458 public Drawable getTrackDrawable() {
459 return mTrackDrawable;
460 }
461
462 /**
463 * Set the drawable used for the switch "thumb" - the piece that the user
464 * can physically touch and drag along the track.
465 *
466 * @param thumb Thumb drawable
467 *
468 * @attr ref android.R.styleable#Switch_thumb
469 */
470 public void setThumbDrawable(Drawable thumb) {
471 mThumbDrawable = thumb;
472 requestLayout();
473 }
474
475 /**
Adam Powelld9c7be62012-03-08 19:43:43 -0800476 * Set the drawable used for the switch "thumb" - the piece that the user
477 * can physically touch and drag along the track.
478 *
Adam Powelldca510e2012-03-08 20:06:39 -0800479 * @param resId Resource ID of a thumb drawable
Adam Powelld9c7be62012-03-08 19:43:43 -0800480 *
481 * @attr ref android.R.styleable#Switch_thumb
482 */
483 public void setThumbResource(int resId) {
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800484 setThumbDrawable(getContext().getDrawable(resId));
Adam Powelld9c7be62012-03-08 19:43:43 -0800485 }
486
487 /**
Adam Powell6c86e1b2012-03-08 15:11:46 -0800488 * Get the drawable used for the switch "thumb" - the piece that the user
489 * can physically touch and drag along the track.
490 *
491 * @return Thumb drawable
492 *
493 * @attr ref android.R.styleable#Switch_thumb
494 */
495 public Drawable getThumbDrawable() {
496 return mThumbDrawable;
497 }
498
499 /**
Alan Viverette661e6362014-05-12 10:55:37 -0700500 * Specifies whether the track should be split by the thumb. When true,
501 * the thumb's optical bounds will be clipped out of the track drawable,
502 * then the thumb will be drawn into the resulting gap.
503 *
504 * @param splitTrack Whether the track should be split by the thumb
505 *
506 * @attr ref android.R.styleable#Switch_splitTrack
507 */
508 public void setSplitTrack(boolean splitTrack) {
509 mSplitTrack = splitTrack;
510 invalidate();
511 }
512
513 /**
514 * Returns whether the track should be split by the thumb.
515 *
516 * @attr ref android.R.styleable#Switch_splitTrack
517 */
518 public boolean getSplitTrack() {
519 return mSplitTrack;
520 }
521
522 /**
Chet Haase150176d2011-08-26 09:54:06 -0700523 * Returns the text displayed when the button is in the checked state.
Adam Powell6c86e1b2012-03-08 15:11:46 -0800524 *
525 * @attr ref android.R.styleable#Switch_textOn
Adam Powell12190b32010-11-28 19:07:53 -0800526 */
527 public CharSequence getTextOn() {
528 return mTextOn;
529 }
530
531 /**
Chet Haase150176d2011-08-26 09:54:06 -0700532 * Sets the text displayed when the button is in the checked state.
Adam Powell6c86e1b2012-03-08 15:11:46 -0800533 *
534 * @attr ref android.R.styleable#Switch_textOn
Adam Powell12190b32010-11-28 19:07:53 -0800535 */
536 public void setTextOn(CharSequence textOn) {
537 mTextOn = textOn;
538 requestLayout();
539 }
540
541 /**
Chet Haase150176d2011-08-26 09:54:06 -0700542 * Returns the text displayed when the button is not in the checked state.
Adam Powell6c86e1b2012-03-08 15:11:46 -0800543 *
544 * @attr ref android.R.styleable#Switch_textOff
Adam Powell12190b32010-11-28 19:07:53 -0800545 */
546 public CharSequence getTextOff() {
547 return mTextOff;
548 }
549
550 /**
Chet Haase150176d2011-08-26 09:54:06 -0700551 * Sets the text displayed when the button is not in the checked state.
Adam Powell6c86e1b2012-03-08 15:11:46 -0800552 *
553 * @attr ref android.R.styleable#Switch_textOff
Adam Powell12190b32010-11-28 19:07:53 -0800554 */
555 public void setTextOff(CharSequence textOff) {
556 mTextOff = textOff;
557 requestLayout();
558 }
559
Alan Viverette2a37cf8d2014-06-19 17:09:10 -0700560 /**
561 * Sets whether the on/off text should be displayed.
562 *
563 * @param showText {@code true} to display on/off text
Alan Viverette0c0dde72014-07-30 13:29:39 -0700564 * @attr ref android.R.styleable#Switch_showText
Alan Viverette2a37cf8d2014-06-19 17:09:10 -0700565 */
566 public void setShowText(boolean showText) {
567 if (mShowText != showText) {
568 mShowText = showText;
569 requestLayout();
570 }
571 }
572
573 /**
574 * @return whether the on/off text should be displayed
Alan Viverette0c0dde72014-07-30 13:29:39 -0700575 * @attr ref android.R.styleable#Switch_showText
Alan Viverette2a37cf8d2014-06-19 17:09:10 -0700576 */
577 public boolean getShowText() {
578 return mShowText;
579 }
580
Adam Powell12190b32010-11-28 19:07:53 -0800581 @Override
582 public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Alan Viverette2a37cf8d2014-06-19 17:09:10 -0700583 if (mShowText) {
584 if (mOnLayout == null) {
585 mOnLayout = makeLayout(mTextOn);
586 }
Alan Viverette5876ff42014-03-03 17:40:46 -0800587
Alan Viverette2a37cf8d2014-06-19 17:09:10 -0700588 if (mOffLayout == null) {
589 mOffLayout = makeLayout(mTextOff);
590 }
Adam Powell12190b32010-11-28 19:07:53 -0800591 }
592
Alan Viverette9b38f6c2014-07-30 02:39:07 +0000593 final Rect padding = mTempRect;
Alan Viverette0c0dde72014-07-30 13:29:39 -0700594 final int thumbWidth;
595 final int thumbHeight;
596 if (mThumbDrawable != null) {
597 // Cached thumb width does not include padding.
598 mThumbDrawable.getPadding(padding);
599 thumbWidth = mThumbDrawable.getIntrinsicWidth() - padding.left - padding.right;
600 thumbHeight = mThumbDrawable.getIntrinsicHeight();
601 } else {
602 thumbWidth = 0;
603 thumbHeight = 0;
604 }
605
606 final int maxTextWidth;
607 if (mShowText) {
608 maxTextWidth = Math.max(mOnLayout.getWidth(), mOffLayout.getWidth())
609 + mThumbTextPadding * 2;
610 } else {
611 maxTextWidth = 0;
612 }
613
614 mThumbWidth = Math.max(maxTextWidth, thumbWidth);
615
616 final int trackHeight;
Alan Viverette4d065a02014-07-11 15:28:38 -0700617 if (mTrackDrawable != null) {
618 mTrackDrawable.getPadding(padding);
619 trackHeight = mTrackDrawable.getIntrinsicHeight();
620 } else {
621 padding.setEmpty();
622 trackHeight = 0;
623 }
624
Alan Viverette0c0dde72014-07-30 13:29:39 -0700625 // Adjust left and right padding to ensure there's enough room for the
626 // thumb's padding (when present).
627 int paddingLeft = padding.left;
628 int paddingRight = padding.right;
Alan Viverette4d065a02014-07-11 15:28:38 -0700629 if (mThumbDrawable != null) {
Alan Viverette0c0dde72014-07-30 13:29:39 -0700630 final Insets inset = mThumbDrawable.getOpticalInsets();
631 paddingLeft = Math.max(paddingLeft, inset.left);
632 paddingRight = Math.max(paddingRight, inset.right);
Alan Viverette4d065a02014-07-11 15:28:38 -0700633 }
Alan Viverette5876ff42014-03-03 17:40:46 -0800634
Adam Powell12190b32010-11-28 19:07:53 -0800635 final int switchWidth = Math.max(mSwitchMinWidth,
Alan Viverette0c0dde72014-07-30 13:29:39 -0700636 2 * mThumbWidth + paddingLeft + paddingRight);
Alan Viverette4d065a02014-07-11 15:28:38 -0700637 final int switchHeight = Math.max(trackHeight, thumbHeight);
Adam Powell12190b32010-11-28 19:07:53 -0800638 mSwitchWidth = switchWidth;
639 mSwitchHeight = switchHeight;
640
641 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
Alan Viverette4d065a02014-07-11 15:28:38 -0700642
Adam Powell12190b32010-11-28 19:07:53 -0800643 final int measuredHeight = getMeasuredHeight();
644 if (measuredHeight < switchHeight) {
Dianne Hackborn189ee182010-12-02 21:48:53 -0800645 setMeasuredDimension(getMeasuredWidthAndState(), switchHeight);
Adam Powell12190b32010-11-28 19:07:53 -0800646 }
647 }
648
Svetoslav Ganov63bce032011-07-23 19:52:17 -0700649 @Override
650 public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
651 super.onPopulateAccessibilityEvent(event);
Alan Viverette2a37cf8d2014-06-19 17:09:10 -0700652
653 final CharSequence text = isChecked() ? mTextOn : mTextOff;
654 if (text != null) {
655 event.getText().add(text);
Svetoslav Ganov76502592011-07-29 10:44:59 -0700656 }
Svetoslav Ganov63bce032011-07-23 19:52:17 -0700657 }
658
Adam Powell12190b32010-11-28 19:07:53 -0800659 private Layout makeLayout(CharSequence text) {
Daniel Sandler4c3308d2012-04-19 11:04:39 -0400660 final CharSequence transformed = (mSwitchTransformationMethod != null)
661 ? mSwitchTransformationMethod.getTransformation(text, this)
662 : text;
663
664 return new StaticLayout(transformed, mTextPaint,
665 (int) Math.ceil(Layout.getDesiredWidth(transformed, mTextPaint)),
Adam Powell12190b32010-11-28 19:07:53 -0800666 Layout.Alignment.ALIGN_NORMAL, 1.f, 0, true);
667 }
668
669 /**
670 * @return true if (x, y) is within the target area of the switch thumb
671 */
672 private boolean hitThumb(float x, float y) {
Alan Viverettecc2688d2013-09-17 17:00:12 -0700673 // Relies on mTempRect, MUST be called first!
674 final int thumbOffset = getThumbOffset();
675
Adam Powell12190b32010-11-28 19:07:53 -0800676 mThumbDrawable.getPadding(mTempRect);
677 final int thumbTop = mSwitchTop - mTouchSlop;
Alan Viverettecc2688d2013-09-17 17:00:12 -0700678 final int thumbLeft = mSwitchLeft + thumbOffset - mTouchSlop;
Adam Powell12190b32010-11-28 19:07:53 -0800679 final int thumbRight = thumbLeft + mThumbWidth +
680 mTempRect.left + mTempRect.right + mTouchSlop;
681 final int thumbBottom = mSwitchBottom + mTouchSlop;
682 return x > thumbLeft && x < thumbRight && y > thumbTop && y < thumbBottom;
683 }
684
685 @Override
686 public boolean onTouchEvent(MotionEvent ev) {
687 mVelocityTracker.addMovement(ev);
688 final int action = ev.getActionMasked();
689 switch (action) {
690 case MotionEvent.ACTION_DOWN: {
691 final float x = ev.getX();
692 final float y = ev.getY();
Gilles Debunnec2ab0d62011-06-13 12:52:48 -0700693 if (isEnabled() && hitThumb(x, y)) {
Adam Powell12190b32010-11-28 19:07:53 -0800694 mTouchMode = TOUCH_MODE_DOWN;
695 mTouchX = x;
696 mTouchY = y;
697 }
698 break;
699 }
700
701 case MotionEvent.ACTION_MOVE: {
702 switch (mTouchMode) {
703 case TOUCH_MODE_IDLE:
704 // Didn't target the thumb, treat normally.
705 break;
706
707 case TOUCH_MODE_DOWN: {
708 final float x = ev.getX();
709 final float y = ev.getY();
710 if (Math.abs(x - mTouchX) > mTouchSlop ||
711 Math.abs(y - mTouchY) > mTouchSlop) {
712 mTouchMode = TOUCH_MODE_DRAGGING;
713 getParent().requestDisallowInterceptTouchEvent(true);
714 mTouchX = x;
715 mTouchY = y;
716 return true;
717 }
718 break;
719 }
720
721 case TOUCH_MODE_DRAGGING: {
722 final float x = ev.getX();
Alan Viverettecc2688d2013-09-17 17:00:12 -0700723 final int thumbScrollRange = getThumbScrollRange();
724 final float thumbScrollOffset = x - mTouchX;
725 float dPos;
726 if (thumbScrollRange != 0) {
727 dPos = thumbScrollOffset / thumbScrollRange;
728 } else {
729 // If the thumb scroll range is empty, just use the
730 // movement direction to snap on or off.
731 dPos = thumbScrollOffset > 0 ? 1 : -1;
732 }
733 if (isLayoutRtl()) {
734 dPos = -dPos;
735 }
736 final float newPos = MathUtils.constrain(mThumbPosition + dPos, 0, 1);
Adam Powell12190b32010-11-28 19:07:53 -0800737 if (newPos != mThumbPosition) {
Adam Powell12190b32010-11-28 19:07:53 -0800738 mTouchX = x;
Alan Viverettecc2688d2013-09-17 17:00:12 -0700739 setThumbPosition(newPos);
Adam Powell12190b32010-11-28 19:07:53 -0800740 }
741 return true;
742 }
743 }
744 break;
745 }
746
747 case MotionEvent.ACTION_UP:
748 case MotionEvent.ACTION_CANCEL: {
749 if (mTouchMode == TOUCH_MODE_DRAGGING) {
750 stopDrag(ev);
Alan Viverettead2f8e32014-05-16 13:28:33 -0700751 // Allow super class to handle pressed state, etc.
752 super.onTouchEvent(ev);
Adam Powell12190b32010-11-28 19:07:53 -0800753 return true;
754 }
755 mTouchMode = TOUCH_MODE_IDLE;
756 mVelocityTracker.clear();
757 break;
758 }
759 }
760
761 return super.onTouchEvent(ev);
762 }
763
764 private void cancelSuperTouch(MotionEvent ev) {
765 MotionEvent cancel = MotionEvent.obtain(ev);
766 cancel.setAction(MotionEvent.ACTION_CANCEL);
767 super.onTouchEvent(cancel);
768 cancel.recycle();
769 }
770
771 /**
772 * Called from onTouchEvent to end a drag operation.
773 *
774 * @param ev Event that triggered the end of drag mode - ACTION_UP or ACTION_CANCEL
775 */
776 private void stopDrag(MotionEvent ev) {
777 mTouchMode = TOUCH_MODE_IDLE;
Adam Powell12190b32010-11-28 19:07:53 -0800778
Alan Viverette86453ff2013-09-26 14:46:08 -0700779 // Commit the change if the event is up and not canceled and the switch
780 // has not been disabled during the drag.
781 final boolean commitChange = ev.getAction() == MotionEvent.ACTION_UP && isEnabled();
782 final boolean newState;
Adam Powell12190b32010-11-28 19:07:53 -0800783 if (commitChange) {
Adam Powell12190b32010-11-28 19:07:53 -0800784 mVelocityTracker.computeCurrentVelocity(1000);
Alan Viverette86453ff2013-09-26 14:46:08 -0700785 final float xvel = mVelocityTracker.getXVelocity();
Adam Powell12190b32010-11-28 19:07:53 -0800786 if (Math.abs(xvel) > mMinFlingVelocity) {
Fabrice Di Meglio28efba32012-06-01 16:52:31 -0700787 newState = isLayoutRtl() ? (xvel < 0) : (xvel > 0);
Adam Powell12190b32010-11-28 19:07:53 -0800788 } else {
789 newState = getTargetCheckedState();
790 }
Adam Powell12190b32010-11-28 19:07:53 -0800791 } else {
Alan Viverette86453ff2013-09-26 14:46:08 -0700792 newState = isChecked();
Adam Powell12190b32010-11-28 19:07:53 -0800793 }
Alan Viverette86453ff2013-09-26 14:46:08 -0700794
795 setChecked(newState);
796 cancelSuperTouch(ev);
Adam Powell12190b32010-11-28 19:07:53 -0800797 }
798
799 private void animateThumbToCheckedState(boolean newCheckedState) {
Alan Viverettecc2688d2013-09-17 17:00:12 -0700800 final float targetPosition = newCheckedState ? 1 : 0;
801 mPositionAnimator = ObjectAnimator.ofFloat(this, THUMB_POS, targetPosition);
802 mPositionAnimator.setDuration(THUMB_ANIMATION_DURATION);
803 mPositionAnimator.setAutoCancel(true);
804 mPositionAnimator.start();
805 }
806
807 private void cancelPositionAnimator() {
808 if (mPositionAnimator != null) {
809 mPositionAnimator.cancel();
810 }
Adam Powell12190b32010-11-28 19:07:53 -0800811 }
812
813 private boolean getTargetCheckedState() {
Alan Viverettecc2688d2013-09-17 17:00:12 -0700814 return mThumbPosition > 0.5f;
Fabrice Di Meglio28efba32012-06-01 16:52:31 -0700815 }
816
Alan Viverettecc2688d2013-09-17 17:00:12 -0700817 /**
818 * Sets the thumb position as a decimal value between 0 (off) and 1 (on).
819 *
820 * @param position new position between [0,1]
821 */
822 private void setThumbPosition(float position) {
823 mThumbPosition = position;
824 invalidate();
825 }
826
827 @Override
828 public void toggle() {
Alan Viverette86453ff2013-09-26 14:46:08 -0700829 setChecked(!isChecked());
Adam Powell12190b32010-11-28 19:07:53 -0800830 }
831
832 @Override
833 public void setChecked(boolean checked) {
834 super.setChecked(checked);
Alan Viverettecc2688d2013-09-17 17:00:12 -0700835
Alan Viverette467d6292014-08-12 15:13:19 -0700836 // Calling the super method may result in setChecked() getting called
837 // recursively with a different value, so load the REAL value...
838 checked = isChecked();
839
Alan Viverette86453ff2013-09-26 14:46:08 -0700840 if (isAttachedToWindow() && isLaidOut()) {
841 animateThumbToCheckedState(checked);
842 } else {
843 // Immediately move the thumb to the new position.
844 cancelPositionAnimator();
845 setThumbPosition(checked ? 1 : 0);
846 }
Adam Powell12190b32010-11-28 19:07:53 -0800847 }
848
849 @Override
850 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
851 super.onLayout(changed, left, top, right, bottom);
852
Alan Viverette0c0dde72014-07-30 13:29:39 -0700853 int opticalInsetLeft = 0;
854 int opticalInsetRight = 0;
855 if (mThumbDrawable != null) {
856 final Rect trackPadding = mTempRect;
857 if (mTrackDrawable != null) {
858 mTrackDrawable.getPadding(trackPadding);
859 } else {
860 trackPadding.setEmpty();
861 }
Fabrice Di Meglio28efba32012-06-01 16:52:31 -0700862
Alan Viverette0c0dde72014-07-30 13:29:39 -0700863 final Insets insets = mThumbDrawable.getOpticalInsets();
864 opticalInsetLeft = Math.max(0, insets.left - trackPadding.left);
865 opticalInsetRight = Math.max(0, insets.right - trackPadding.right);
Alan Viverette8bb39902014-07-29 17:22:30 -0700866 }
867
Alan Viverette0c0dde72014-07-30 13:29:39 -0700868 final int switchRight;
869 final int switchLeft;
870 if (isLayoutRtl()) {
871 switchLeft = getPaddingLeft() + opticalInsetLeft;
872 switchRight = switchLeft + mSwitchWidth - opticalInsetLeft - opticalInsetRight;
873 } else {
874 switchRight = getWidth() - getPaddingRight() - opticalInsetRight;
875 switchLeft = switchRight - mSwitchWidth + opticalInsetLeft + opticalInsetRight;
876 }
877
878 final int switchTop;
879 final int switchBottom;
Adam Powell12190b32010-11-28 19:07:53 -0800880 switch (getGravity() & Gravity.VERTICAL_GRAVITY_MASK) {
881 default:
882 case Gravity.TOP:
883 switchTop = getPaddingTop();
884 switchBottom = switchTop + mSwitchHeight;
885 break;
886
887 case Gravity.CENTER_VERTICAL:
888 switchTop = (getPaddingTop() + getHeight() - getPaddingBottom()) / 2 -
889 mSwitchHeight / 2;
890 switchBottom = switchTop + mSwitchHeight;
891 break;
892
893 case Gravity.BOTTOM:
894 switchBottom = getHeight() - getPaddingBottom();
895 switchTop = switchBottom - mSwitchHeight;
896 break;
897 }
898
899 mSwitchLeft = switchLeft;
900 mSwitchTop = switchTop;
901 mSwitchBottom = switchBottom;
902 mSwitchRight = switchRight;
903 }
904
905 @Override
Alan Viverettead2f8e32014-05-16 13:28:33 -0700906 public void draw(Canvas c) {
Alan Viverette4d065a02014-07-11 15:28:38 -0700907 final Rect padding = mTempRect;
Alan Viverette5876ff42014-03-03 17:40:46 -0800908 final int switchLeft = mSwitchLeft;
909 final int switchTop = mSwitchTop;
910 final int switchRight = mSwitchRight;
911 final int switchBottom = mSwitchBottom;
Alan Viverette0c0dde72014-07-30 13:29:39 -0700912
913 int thumbInitialLeft = switchLeft + getThumbOffset();
914
915 final Insets thumbInsets;
916 if (mThumbDrawable != null) {
917 thumbInsets = mThumbDrawable.getOpticalInsets();
918 } else {
919 thumbInsets = Insets.NONE;
Alan Viverette8bb39902014-07-29 17:22:30 -0700920 }
Alan Viverettecc2688d2013-09-17 17:00:12 -0700921
Alan Viverette0c0dde72014-07-30 13:29:39 -0700922 // Layout the track.
923 if (mTrackDrawable != null) {
924 mTrackDrawable.getPadding(padding);
Alan Viverette9b38f6c2014-07-30 02:39:07 +0000925
Alan Viverette0c0dde72014-07-30 13:29:39 -0700926 // Adjust thumb position for track padding.
927 thumbInitialLeft += padding.left;
928
929 // If necessary, offset by the optical insets of the thumb asset.
930 int trackLeft = switchLeft;
931 int trackTop = switchTop;
932 int trackRight = switchRight;
933 int trackBottom = switchBottom;
934 if (thumbInsets != Insets.NONE) {
935 if (thumbInsets.left > padding.left) {
936 trackLeft += thumbInsets.left - padding.left;
937 }
938 if (thumbInsets.top > padding.top) {
939 trackTop += thumbInsets.top - padding.top;
940 }
941 if (thumbInsets.right > padding.right) {
942 trackRight -= thumbInsets.right - padding.right;
943 }
944 if (thumbInsets.bottom > padding.bottom) {
945 trackBottom -= thumbInsets.bottom - padding.bottom;
946 }
947 }
948 mTrackDrawable.setBounds(trackLeft, trackTop, trackRight, trackBottom);
949 }
Alan Viverette9b38f6c2014-07-30 02:39:07 +0000950
Alan Viverette661e6362014-05-12 10:55:37 -0700951 // Layout the thumb.
Alan Viverette4d065a02014-07-11 15:28:38 -0700952 if (mThumbDrawable != null) {
953 mThumbDrawable.getPadding(padding);
Alan Viverette0c0dde72014-07-30 13:29:39 -0700954
955 final int thumbLeft = thumbInitialLeft - padding.left;
956 final int thumbRight = thumbInitialLeft + mThumbWidth + padding.right;
Alan Viverette4d065a02014-07-11 15:28:38 -0700957 mThumbDrawable.setBounds(thumbLeft, switchTop, thumbRight, switchBottom);
Alan Viverette61956602014-04-22 19:07:06 -0700958
Alan Viverette4d065a02014-07-11 15:28:38 -0700959 final Drawable background = getBackground();
960 if (background != null) {
961 background.setHotspotBounds(thumbLeft, switchTop, thumbRight, switchBottom);
962 }
Alan Viverette61956602014-04-22 19:07:06 -0700963 }
964
Alan Viverettead2f8e32014-05-16 13:28:33 -0700965 // Draw the background.
966 super.draw(c);
967 }
968
969 @Override
970 protected void onDraw(Canvas canvas) {
Alan Viverette61956602014-04-22 19:07:06 -0700971 super.onDraw(canvas);
972
Alan Viverette4d065a02014-07-11 15:28:38 -0700973 final Rect padding = mTempRect;
Alan Viverettead2f8e32014-05-16 13:28:33 -0700974 final Drawable trackDrawable = mTrackDrawable;
Alan Viverette4d065a02014-07-11 15:28:38 -0700975 if (trackDrawable != null) {
976 trackDrawable.getPadding(padding);
977 } else {
978 padding.setEmpty();
979 }
Alan Viverettead2f8e32014-05-16 13:28:33 -0700980
981 final int switchTop = mSwitchTop;
982 final int switchBottom = mSwitchBottom;
Alan Viverette4d065a02014-07-11 15:28:38 -0700983 final int switchInnerTop = switchTop + padding.top;
Alan Viverette4d065a02014-07-11 15:28:38 -0700984 final int switchInnerBottom = switchBottom - padding.bottom;
Alan Viverettead2f8e32014-05-16 13:28:33 -0700985
Alan Viverette4d065a02014-07-11 15:28:38 -0700986 final Drawable thumbDrawable = mThumbDrawable;
987 if (trackDrawable != null) {
988 if (mSplitTrack && thumbDrawable != null) {
989 final Insets insets = thumbDrawable.getOpticalInsets();
990 thumbDrawable.copyBounds(padding);
991 padding.left += insets.left;
992 padding.right -= insets.right;
Alan Viverette661e6362014-05-12 10:55:37 -0700993
Alan Viverette4d065a02014-07-11 15:28:38 -0700994 final int saveCount = canvas.save();
995 canvas.clipRect(padding, Op.DIFFERENCE);
996 trackDrawable.draw(canvas);
997 canvas.restoreToCount(saveCount);
998 } else {
999 trackDrawable.draw(canvas);
1000 }
Alan Viverette661e6362014-05-12 10:55:37 -07001001 }
Alan Viverette61956602014-04-22 19:07:06 -07001002
1003 final int saveCount = canvas.save();
Alan Viverette4d065a02014-07-11 15:28:38 -07001004
1005 if (thumbDrawable != null) {
Alan Viverette4d065a02014-07-11 15:28:38 -07001006 thumbDrawable.draw(canvas);
1007 }
Adam Powell12190b32010-11-28 19:07:53 -08001008
Alan Viverette5876ff42014-03-03 17:40:46 -08001009 final Layout switchText = getTargetCheckedState() ? mOnLayout : mOffLayout;
Fabrice Di Megliobe06e322012-09-11 17:42:45 -07001010 if (switchText != null) {
Alan Viverette661e6362014-05-12 10:55:37 -07001011 final int drawableState[] = getDrawableState();
1012 if (mTextColors != null) {
1013 mTextPaint.setColor(mTextColors.getColorForState(drawableState, 0));
1014 }
1015 mTextPaint.drawableState = drawableState;
1016
Alan Viverette4d065a02014-07-11 15:28:38 -07001017 final int cX;
1018 if (thumbDrawable != null) {
1019 final Rect bounds = thumbDrawable.getBounds();
1020 cX = bounds.left + bounds.right;
1021 } else {
Alan Viverettedec17292014-07-12 00:26:36 -07001022 cX = getWidth();
Alan Viverette4d065a02014-07-11 15:28:38 -07001023 }
1024
1025 final int left = cX / 2 - switchText.getWidth() / 2;
Alan Viverette5876ff42014-03-03 17:40:46 -08001026 final int top = (switchInnerTop + switchInnerBottom) / 2 - switchText.getHeight() / 2;
1027 canvas.translate(left, top);
Fabrice Di Megliobe06e322012-09-11 17:42:45 -07001028 switchText.draw(canvas);
1029 }
Adam Powell12190b32010-11-28 19:07:53 -08001030
Alan Viverette5876ff42014-03-03 17:40:46 -08001031 canvas.restoreToCount(saveCount);
Adam Powell12190b32010-11-28 19:07:53 -08001032 }
1033
1034 @Override
Fabrice Di Meglio28efba32012-06-01 16:52:31 -07001035 public int getCompoundPaddingLeft() {
1036 if (!isLayoutRtl()) {
1037 return super.getCompoundPaddingLeft();
1038 }
1039 int padding = super.getCompoundPaddingLeft() + mSwitchWidth;
1040 if (!TextUtils.isEmpty(getText())) {
1041 padding += mSwitchPadding;
1042 }
1043 return padding;
1044 }
1045
1046 @Override
Adam Powell12190b32010-11-28 19:07:53 -08001047 public int getCompoundPaddingRight() {
Fabrice Di Meglio28efba32012-06-01 16:52:31 -07001048 if (isLayoutRtl()) {
1049 return super.getCompoundPaddingRight();
1050 }
Adam Powell12190b32010-11-28 19:07:53 -08001051 int padding = super.getCompoundPaddingRight() + mSwitchWidth;
1052 if (!TextUtils.isEmpty(getText())) {
1053 padding += mSwitchPadding;
1054 }
1055 return padding;
1056 }
1057
Alan Viverettecc2688d2013-09-17 17:00:12 -07001058 /**
1059 * Translates thumb position to offset according to current RTL setting and
Alan Viverette0c0dde72014-07-30 13:29:39 -07001060 * thumb scroll range. Accounts for both track and thumb padding.
Alan Viverettecc2688d2013-09-17 17:00:12 -07001061 *
1062 * @return thumb offset
1063 */
1064 private int getThumbOffset() {
1065 final float thumbPosition;
1066 if (isLayoutRtl()) {
1067 thumbPosition = 1 - mThumbPosition;
1068 } else {
1069 thumbPosition = mThumbPosition;
1070 }
1071 return (int) (thumbPosition * getThumbScrollRange() + 0.5f);
1072 }
1073
Adam Powell12190b32010-11-28 19:07:53 -08001074 private int getThumbScrollRange() {
Alan Viverette4d065a02014-07-11 15:28:38 -07001075 if (mTrackDrawable != null) {
Alan Viverette0c0dde72014-07-30 13:29:39 -07001076 final Rect padding = mTempRect;
1077 mTrackDrawable.getPadding(padding);
1078
1079 final Insets insets;
1080 if (mThumbDrawable != null) {
1081 insets = mThumbDrawable.getOpticalInsets();
1082 } else {
1083 insets = Insets.NONE;
1084 }
1085
1086 return mSwitchWidth - mThumbWidth - padding.left - padding.right
1087 - insets.left - insets.right;
Alan Viverette4d065a02014-07-11 15:28:38 -07001088 } else {
Adam Powell12190b32010-11-28 19:07:53 -08001089 return 0;
1090 }
Adam Powell12190b32010-11-28 19:07:53 -08001091 }
1092
1093 @Override
1094 protected int[] onCreateDrawableState(int extraSpace) {
1095 final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
1096 if (isChecked()) {
1097 mergeDrawableStates(drawableState, CHECKED_STATE_SET);
1098 }
1099 return drawableState;
1100 }
1101
1102 @Override
1103 protected void drawableStateChanged() {
1104 super.drawableStateChanged();
1105
Alan Viverette661e6362014-05-12 10:55:37 -07001106 final int[] myDrawableState = getDrawableState();
Adam Powell12190b32010-11-28 19:07:53 -08001107
Alan Viverette2356c5e2014-05-22 22:43:59 -07001108 if (mThumbDrawable != null) {
1109 mThumbDrawable.setState(myDrawableState);
Alan Viverette661e6362014-05-12 10:55:37 -07001110 }
1111
1112 if (mTrackDrawable != null) {
1113 mTrackDrawable.setState(myDrawableState);
1114 }
Adam Powell12190b32010-11-28 19:07:53 -08001115
1116 invalidate();
1117 }
1118
Alan Viverettecebc6ba2014-06-13 15:52:13 -07001119 @Override
Alan Viverette8de14942014-06-18 18:05:15 -07001120 public void drawableHotspotChanged(float x, float y) {
1121 super.drawableHotspotChanged(x, y);
Alan Viverettecebc6ba2014-06-13 15:52:13 -07001122
1123 if (mThumbDrawable != null) {
1124 mThumbDrawable.setHotspot(x, y);
1125 }
1126
1127 if (mTrackDrawable != null) {
1128 mTrackDrawable.setHotspot(x, y);
1129 }
1130 }
1131
Adam Powell12190b32010-11-28 19:07:53 -08001132 @Override
1133 protected boolean verifyDrawable(Drawable who) {
1134 return super.verifyDrawable(who) || who == mThumbDrawable || who == mTrackDrawable;
1135 }
1136
1137 @Override
1138 public void jumpDrawablesToCurrentState() {
1139 super.jumpDrawablesToCurrentState();
Alan Viverette4d065a02014-07-11 15:28:38 -07001140
1141 if (mThumbDrawable != null) {
1142 mThumbDrawable.jumpToCurrentState();
1143 }
1144
1145 if (mTrackDrawable != null) {
1146 mTrackDrawable.jumpToCurrentState();
1147 }
1148
1149 if (mPositionAnimator != null && mPositionAnimator.isRunning()) {
1150 mPositionAnimator.end();
1151 mPositionAnimator = null;
1152 }
Adam Powell12190b32010-11-28 19:07:53 -08001153 }
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -08001154
1155 @Override
1156 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
1157 super.onInitializeAccessibilityEvent(event);
1158 event.setClassName(Switch.class.getName());
1159 }
1160
1161 @Override
1162 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
1163 super.onInitializeAccessibilityNodeInfo(info);
1164 info.setClassName(Switch.class.getName());
Svetoslav Ganov78bcc152012-04-12 17:17:19 -07001165 CharSequence switchText = isChecked() ? mTextOn : mTextOff;
1166 if (!TextUtils.isEmpty(switchText)) {
1167 CharSequence oldText = info.getText();
1168 if (TextUtils.isEmpty(oldText)) {
1169 info.setText(switchText);
1170 } else {
1171 StringBuilder newText = new StringBuilder();
1172 newText.append(oldText).append(' ').append(switchText);
1173 info.setText(newText);
1174 }
1175 }
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -08001176 }
Alan Viverettecc2688d2013-09-17 17:00:12 -07001177
1178 private static final FloatProperty<Switch> THUMB_POS = new FloatProperty<Switch>("thumbPos") {
1179 @Override
1180 public Float get(Switch object) {
1181 return object.mThumbPosition;
1182 }
1183
1184 @Override
1185 public void setValue(Switch object, float value) {
1186 object.setThumbPosition(value);
1187 }
1188 };
Adam Powell12190b32010-11-28 19:07:53 -08001189}