blob: e1fd77624a29302adadf6e5950e747558b94f9b6 [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;
Tor Norbye7b9c9122013-05-30 16:48:33 -070020import android.annotation.DrawableRes;
Alan Viverettef6d87ec2016-03-11 10:09:14 -050021import android.annotation.NonNull;
Alan Viverettee7eee642015-01-29 14:27:49 -080022import android.annotation.Nullable;
Tor Norbye7b9c9122013-05-30 16:48:33 -070023import android.annotation.StyleRes;
Artur Satayeved5a6ae2019-12-10 17:47:54 +000024import android.compat.annotation.UnsupportedAppUsage;
Adam Powell12190b32010-11-28 19:07:53 -080025import android.content.Context;
26import android.content.res.ColorStateList;
27import android.content.res.Resources;
28import android.content.res.TypedArray;
Nader Jawad8e31c3e2019-04-14 21:58:04 -070029import android.graphics.BlendMode;
Adam Powell12190b32010-11-28 19:07:53 -080030import android.graphics.Canvas;
Alan Viverette661e6362014-05-12 10:55:37 -070031import android.graphics.Insets;
Chris Craik6a49dde2015-05-12 10:28:14 -070032import android.graphics.Paint;
Alan Viverettee7eee642015-01-29 14:27:49 -080033import android.graphics.PorterDuff;
Adam Powell12190b32010-11-28 19:07:53 -080034import android.graphics.Rect;
Alan Viverette661e6362014-05-12 10:55:37 -070035import android.graphics.Region.Op;
Aurimas Liutikas99441c52016-10-11 16:48:32 -070036import android.graphics.Typeface;
Adam Powell12190b32010-11-28 19:07:53 -080037import android.graphics.drawable.Drawable;
Roozbeh Pournader5caf5a62017-08-22 18:08:09 -070038import android.os.Build.VERSION_CODES;
Adam Powell12190b32010-11-28 19:07:53 -080039import android.text.Layout;
40import android.text.StaticLayout;
41import android.text.TextPaint;
42import android.text.TextUtils;
Daniel Sandler4c3308d2012-04-19 11:04:39 -040043import android.text.method.AllCapsTransformationMethod;
44import android.text.method.TransformationMethod2;
Adam Powell12190b32010-11-28 19:07:53 -080045import android.util.AttributeSet;
Alan Viverettecc2688d2013-09-17 17:00:12 -070046import android.util.FloatProperty;
47import android.util.MathUtils;
Adam Powell12190b32010-11-28 19:07:53 -080048import android.view.Gravity;
49import android.view.MotionEvent;
Alan Viveretted4e77902014-10-27 17:50:51 -070050import android.view.SoundEffectConstants;
Adam Powell12190b32010-11-28 19:07:53 -080051import android.view.VelocityTracker;
52import android.view.ViewConfiguration;
Aurimas Liutikas99441c52016-10-11 16:48:32 -070053import android.view.ViewStructure;
Svetoslav Ganov63bce032011-07-23 19:52:17 -070054import android.view.accessibility.AccessibilityEvent;
Ashley Rose55f9f922019-01-28 19:29:36 -050055import android.view.inspector.InspectableProperty;
Adam Powell12190b32010-11-28 19:07:53 -080056
Adam Powellbe0a4532010-11-29 17:47:48 -080057import com.android.internal.R;
58
Adam Powell12190b32010-11-28 19:07:53 -080059/**
60 * A Switch is a two-state toggle switch widget that can select between two
61 * options. The user may drag the "thumb" back and forth to choose the selected option,
Chet Haase150176d2011-08-26 09:54:06 -070062 * or simply tap to toggle as if it were a checkbox. The {@link #setText(CharSequence) text}
63 * property controls the text displayed in the label for the switch, whereas the
64 * {@link #setTextOff(CharSequence) off} and {@link #setTextOn(CharSequence) on} text
65 * controls the text on the thumb. Similarly, the
66 * {@link #setTextAppearance(android.content.Context, int) textAppearance} and the related
67 * setTypeface() methods control the typeface and style of label text, whereas the
68 * {@link #setSwitchTextAppearance(android.content.Context, int) switchTextAppearance} and
Andrew Solovay07e70212015-07-08 12:49:21 -070069 * the related setSwitchTypeface() methods control that of the thumb.
Adam Powell12190b32010-11-28 19:07:53 -080070 *
Mark Lu34040322016-08-30 18:12:30 -070071 * <p>{@link android.support.v7.widget.SwitchCompat} is a version of
72 * the Switch widget which runs on devices back to API 7.</p>
73 *
Scott Main4c359b72012-07-24 15:51:27 -070074 * <p>See the <a href="{@docRoot}guide/topics/ui/controls/togglebutton.html">Toggle Buttons</a>
75 * guide.</p>
76 *
77 * @attr ref android.R.styleable#Switch_textOn
78 * @attr ref android.R.styleable#Switch_textOff
79 * @attr ref android.R.styleable#Switch_switchMinWidth
80 * @attr ref android.R.styleable#Switch_switchPadding
81 * @attr ref android.R.styleable#Switch_switchTextAppearance
82 * @attr ref android.R.styleable#Switch_thumb
83 * @attr ref android.R.styleable#Switch_thumbTextPadding
84 * @attr ref android.R.styleable#Switch_track
Adam Powell12190b32010-11-28 19:07:53 -080085 */
86public class Switch extends CompoundButton {
Alan Viverettecc2688d2013-09-17 17:00:12 -070087 private static final int THUMB_ANIMATION_DURATION = 250;
88
Adam Powell12190b32010-11-28 19:07:53 -080089 private static final int TOUCH_MODE_IDLE = 0;
90 private static final int TOUCH_MODE_DOWN = 1;
91 private static final int TOUCH_MODE_DRAGGING = 2;
92
93 // Enum for the "typeface" XML parameter.
94 private static final int SANS = 1;
95 private static final int SERIF = 2;
96 private static final int MONOSPACE = 3;
97
Mathew Inwood978c6e22018-08-21 15:58:55 +010098 @UnsupportedAppUsage
Adam Powell12190b32010-11-28 19:07:53 -080099 private Drawable mThumbDrawable;
Alan Viverettee7eee642015-01-29 14:27:49 -0800100 private ColorStateList mThumbTintList = null;
Nader Jawad8e31c3e2019-04-14 21:58:04 -0700101 private BlendMode mThumbBlendMode = null;
Alan Viverettee7eee642015-01-29 14:27:49 -0800102 private boolean mHasThumbTint = false;
103 private boolean mHasThumbTintMode = false;
104
Mathew Inwood978c6e22018-08-21 15:58:55 +0100105 @UnsupportedAppUsage
Adam Powell12190b32010-11-28 19:07:53 -0800106 private Drawable mTrackDrawable;
Alan Viverettee7eee642015-01-29 14:27:49 -0800107 private ColorStateList mTrackTintList = null;
Nader Jawad8e31c3e2019-04-14 21:58:04 -0700108 private BlendMode mTrackBlendMode = null;
Alan Viverettee7eee642015-01-29 14:27:49 -0800109 private boolean mHasTrackTint = false;
110 private boolean mHasTrackTintMode = false;
111
Adam Powell12190b32010-11-28 19:07:53 -0800112 private int mThumbTextPadding;
Mathew Inwood978c6e22018-08-21 15:58:55 +0100113 @UnsupportedAppUsage
Adam Powell12190b32010-11-28 19:07:53 -0800114 private int mSwitchMinWidth;
115 private int mSwitchPadding;
Alan Viverette661e6362014-05-12 10:55:37 -0700116 private boolean mSplitTrack;
Adam Powell12190b32010-11-28 19:07:53 -0800117 private CharSequence mTextOn;
118 private CharSequence mTextOff;
Alan Viverette2a37cf8d2014-06-19 17:09:10 -0700119 private boolean mShowText;
Roozbeh Pournader5caf5a62017-08-22 18:08:09 -0700120 private boolean mUseFallbackLineSpacing;
Adam Powell12190b32010-11-28 19:07:53 -0800121
122 private int mTouchMode;
123 private int mTouchSlop;
124 private float mTouchX;
125 private float mTouchY;
126 private VelocityTracker mVelocityTracker = VelocityTracker.obtain();
127 private int mMinFlingVelocity;
128
129 private float mThumbPosition;
Alan Viverette8bb39902014-07-29 17:22:30 -0700130
Alan Viverette0c0dde72014-07-30 13:29:39 -0700131 /**
132 * Width required to draw the switch track and thumb. Includes padding and
133 * optical bounds for both the track and thumb.
134 */
Mathew Inwood978c6e22018-08-21 15:58:55 +0100135 @UnsupportedAppUsage
Alan Viverette0c0dde72014-07-30 13:29:39 -0700136 private int mSwitchWidth;
137
138 /**
139 * Height required to draw the switch track and thumb. Includes padding and
140 * optical bounds for both the track and thumb.
141 */
Mathew Inwood978c6e22018-08-21 15:58:55 +0100142 @UnsupportedAppUsage
Alan Viverette0c0dde72014-07-30 13:29:39 -0700143 private int mSwitchHeight;
144
145 /**
146 * Width of the thumb's content region. Does not include padding or
147 * optical bounds.
148 */
Mathew Inwood978c6e22018-08-21 15:58:55 +0100149 @UnsupportedAppUsage
Alan Viverette0c0dde72014-07-30 13:29:39 -0700150 private int mThumbWidth;
151
152 /** Left bound for drawing the switch track and thumb. */
Adam Powell12190b32010-11-28 19:07:53 -0800153 private int mSwitchLeft;
Alan Viverette0c0dde72014-07-30 13:29:39 -0700154
155 /** Top bound for drawing the switch track and thumb. */
Adam Powell12190b32010-11-28 19:07:53 -0800156 private int mSwitchTop;
Alan Viverette0c0dde72014-07-30 13:29:39 -0700157
158 /** Right bound for drawing the switch track and thumb. */
Adam Powell12190b32010-11-28 19:07:53 -0800159 private int mSwitchRight;
Alan Viverette0c0dde72014-07-30 13:29:39 -0700160
161 /** Bottom bound for drawing the switch track and thumb. */
Adam Powell12190b32010-11-28 19:07:53 -0800162 private int mSwitchBottom;
163
164 private TextPaint mTextPaint;
165 private ColorStateList mTextColors;
Mathew Inwood978c6e22018-08-21 15:58:55 +0100166 @UnsupportedAppUsage
Adam Powell12190b32010-11-28 19:07:53 -0800167 private Layout mOnLayout;
Mathew Inwood978c6e22018-08-21 15:58:55 +0100168 @UnsupportedAppUsage
Adam Powell12190b32010-11-28 19:07:53 -0800169 private Layout mOffLayout;
Daniel Sandler4c3308d2012-04-19 11:04:39 -0400170 private TransformationMethod2 mSwitchTransformationMethod;
Alan Viverettecc2688d2013-09-17 17:00:12 -0700171 private ObjectAnimator mPositionAnimator;
Adam Powell12190b32010-11-28 19:07:53 -0800172
Adam Powellbe0a4532010-11-29 17:47:48 -0800173 @SuppressWarnings("hiding")
Adam Powell12190b32010-11-28 19:07:53 -0800174 private final Rect mTempRect = new Rect();
175
176 private static final int[] CHECKED_STATE_SET = {
177 R.attr.state_checked
178 };
179
180 /**
181 * Construct a new Switch with default styling.
182 *
183 * @param context The Context that will determine this widget's theming.
184 */
185 public Switch(Context context) {
186 this(context, null);
187 }
188
189 /**
190 * Construct a new Switch with default styling, overriding specific style
191 * attributes as requested.
192 *
193 * @param context The Context that will determine this widget's theming.
194 * @param attrs Specification of attributes that should deviate from default styling.
195 */
196 public Switch(Context context, AttributeSet attrs) {
197 this(context, attrs, com.android.internal.R.attr.switchStyle);
198 }
199
200 /**
201 * Construct a new Switch with a default style determined by the given theme attribute,
202 * overriding specific style attributes as requested.
203 *
204 * @param context The Context that will determine this widget's theming.
205 * @param attrs Specification of attributes that should deviate from the default styling.
Alan Viverette617feb92013-09-09 18:09:13 -0700206 * @param defStyleAttr An attribute in the current theme that contains a
207 * reference to a style resource that supplies default values for
208 * the view. Can be 0 to not look for defaults.
Adam Powell12190b32010-11-28 19:07:53 -0800209 */
Alan Viverette617feb92013-09-09 18:09:13 -0700210 public Switch(Context context, AttributeSet attrs, int defStyleAttr) {
211 this(context, attrs, defStyleAttr, 0);
212 }
213
214
215 /**
216 * Construct a new Switch with a default style determined by the given theme
217 * attribute or style resource, overriding specific style attributes as
218 * requested.
219 *
220 * @param context The Context that will determine this widget's theming.
221 * @param attrs Specification of attributes that should deviate from the
222 * default styling.
223 * @param defStyleAttr An attribute in the current theme that contains a
224 * reference to a style resource that supplies default values for
225 * the view. Can be 0 to not look for defaults.
226 * @param defStyleRes A resource identifier of a style resource that
227 * supplies default values for the view, used only if
228 * defStyleAttr is 0 or can not be found in the theme. Can be 0
229 * to not look for defaults.
230 */
231 public Switch(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
232 super(context, attrs, defStyleAttr, defStyleRes);
Adam Powell12190b32010-11-28 19:07:53 -0800233
Chris Craik6a49dde2015-05-12 10:28:14 -0700234 mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
Alan Viverette661e6362014-05-12 10:55:37 -0700235
236 final Resources res = getResources();
Adam Powell12190b32010-11-28 19:07:53 -0800237 mTextPaint.density = res.getDisplayMetrics().density;
238 mTextPaint.setCompatibilityScaling(res.getCompatibilityInfo().applicationScale);
239
Alan Viverette617feb92013-09-09 18:09:13 -0700240 final TypedArray a = context.obtainStyledAttributes(
241 attrs, com.android.internal.R.styleable.Switch, defStyleAttr, defStyleRes);
Aurimas Liutikasab324cf2019-02-07 16:46:38 -0800242 saveAttributeDataForStyleable(context, com.android.internal.R.styleable.Switch,
243 attrs, a, defStyleAttr, defStyleRes);
Chet Haase150176d2011-08-26 09:54:06 -0700244 mThumbDrawable = a.getDrawable(com.android.internal.R.styleable.Switch_thumb);
Alan Viveretteb0674052014-09-26 16:12:16 -0700245 if (mThumbDrawable != null) {
246 mThumbDrawable.setCallback(this);
247 }
Chet Haase150176d2011-08-26 09:54:06 -0700248 mTrackDrawable = a.getDrawable(com.android.internal.R.styleable.Switch_track);
Alan Viveretteb0674052014-09-26 16:12:16 -0700249 if (mTrackDrawable != null) {
250 mTrackDrawable.setCallback(this);
251 }
Adam Powell12190b32010-11-28 19:07:53 -0800252 mTextOn = a.getText(com.android.internal.R.styleable.Switch_textOn);
253 mTextOff = a.getText(com.android.internal.R.styleable.Switch_textOff);
Alan Viverette2a37cf8d2014-06-19 17:09:10 -0700254 mShowText = a.getBoolean(com.android.internal.R.styleable.Switch_showText, true);
Adam Powell12190b32010-11-28 19:07:53 -0800255 mThumbTextPadding = a.getDimensionPixelSize(
256 com.android.internal.R.styleable.Switch_thumbTextPadding, 0);
257 mSwitchMinWidth = a.getDimensionPixelSize(
258 com.android.internal.R.styleable.Switch_switchMinWidth, 0);
259 mSwitchPadding = a.getDimensionPixelSize(
260 com.android.internal.R.styleable.Switch_switchPadding, 0);
Alan Viverette661e6362014-05-12 10:55:37 -0700261 mSplitTrack = a.getBoolean(com.android.internal.R.styleable.Switch_splitTrack, false);
Adam Powell12190b32010-11-28 19:07:53 -0800262
Roozbeh Pournader60f555c2017-09-21 12:54:55 -0700263 mUseFallbackLineSpacing = context.getApplicationInfo().targetSdkVersion >= VERSION_CODES.P;
Roozbeh Pournader5caf5a62017-08-22 18:08:09 -0700264
Jun Mukai9fb302c2015-06-24 18:31:06 -0700265 ColorStateList thumbTintList = a.getColorStateList(
266 com.android.internal.R.styleable.Switch_thumbTint);
267 if (thumbTintList != null) {
268 mThumbTintList = thumbTintList;
269 mHasThumbTint = true;
270 }
Nader Jawad8e31c3e2019-04-14 21:58:04 -0700271 BlendMode thumbTintMode = Drawable.parseBlendMode(
272 a.getInt(com.android.internal.R.styleable.Switch_thumbTintMode, -1),
273 null);
274 if (mThumbBlendMode != thumbTintMode) {
275 mThumbBlendMode = thumbTintMode;
Jun Mukai9fb302c2015-06-24 18:31:06 -0700276 mHasThumbTintMode = true;
277 }
278 if (mHasThumbTint || mHasThumbTintMode) {
279 applyThumbTint();
280 }
281
282 ColorStateList trackTintList = a.getColorStateList(
283 com.android.internal.R.styleable.Switch_trackTint);
284 if (trackTintList != null) {
285 mTrackTintList = trackTintList;
286 mHasTrackTint = true;
287 }
Nader Jawad8e31c3e2019-04-14 21:58:04 -0700288 BlendMode trackTintMode = Drawable.parseBlendMode(
289 a.getInt(com.android.internal.R.styleable.Switch_trackTintMode, -1),
290 null);
291 if (mTrackBlendMode != trackTintMode) {
292 mTrackBlendMode = trackTintMode;
Jun Mukai9fb302c2015-06-24 18:31:06 -0700293 mHasTrackTintMode = true;
294 }
295 if (mHasTrackTint || mHasTrackTintMode) {
296 applyTrackTint();
297 }
298
Alan Viverette661e6362014-05-12 10:55:37 -0700299 final int appearance = a.getResourceId(
Adam Powell12190b32010-11-28 19:07:53 -0800300 com.android.internal.R.styleable.Switch_switchTextAppearance, 0);
301 if (appearance != 0) {
Chet Haase150176d2011-08-26 09:54:06 -0700302 setSwitchTextAppearance(context, appearance);
Adam Powell12190b32010-11-28 19:07:53 -0800303 }
304 a.recycle();
305
Alan Viverette661e6362014-05-12 10:55:37 -0700306 final ViewConfiguration config = ViewConfiguration.get(context);
Adam Powell12190b32010-11-28 19:07:53 -0800307 mTouchSlop = config.getScaledTouchSlop();
308 mMinFlingVelocity = config.getScaledMinimumFlingVelocity();
309
310 // Refresh display with current params
Gilles Debunnee724ee42011-08-31 11:20:27 -0700311 refreshDrawableState();
yingleiw6a55e062019-12-16 15:11:26 -0800312 // Default state is derived from on/off-text, so state has to be updated when on/off-text
313 // are updated.
314 setDefaultStateDescritption();
Adam Powell12190b32010-11-28 19:07:53 -0800315 setChecked(isChecked());
316 }
317
318 /**
319 * Sets the switch text color, size, style, hint color, and highlight color
320 * from the specified TextAppearance resource.
Adam Powell6c86e1b2012-03-08 15:11:46 -0800321 *
322 * @attr ref android.R.styleable#Switch_switchTextAppearance
Adam Powell12190b32010-11-28 19:07:53 -0800323 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700324 public void setSwitchTextAppearance(Context context, @StyleRes int resid) {
Adam Powell12190b32010-11-28 19:07:53 -0800325 TypedArray appearance =
Chet Haase150176d2011-08-26 09:54:06 -0700326 context.obtainStyledAttributes(resid,
Adam Powell12190b32010-11-28 19:07:53 -0800327 com.android.internal.R.styleable.TextAppearance);
328
329 ColorStateList colors;
330 int ts;
331
332 colors = appearance.getColorStateList(com.android.internal.R.styleable.
333 TextAppearance_textColor);
334 if (colors != null) {
335 mTextColors = colors;
Chet Haase150176d2011-08-26 09:54:06 -0700336 } else {
337 // If no color set in TextAppearance, default to the view's textColor
338 mTextColors = getTextColors();
Adam Powell12190b32010-11-28 19:07:53 -0800339 }
340
341 ts = appearance.getDimensionPixelSize(com.android.internal.R.styleable.
342 TextAppearance_textSize, 0);
343 if (ts != 0) {
344 if (ts != mTextPaint.getTextSize()) {
345 mTextPaint.setTextSize(ts);
346 requestLayout();
347 }
348 }
349
350 int typefaceIndex, styleIndex;
351
352 typefaceIndex = appearance.getInt(com.android.internal.R.styleable.
353 TextAppearance_typeface, -1);
354 styleIndex = appearance.getInt(com.android.internal.R.styleable.
355 TextAppearance_textStyle, -1);
356
357 setSwitchTypefaceByIndex(typefaceIndex, styleIndex);
358
Daniel Sandler4c3308d2012-04-19 11:04:39 -0400359 boolean allCaps = appearance.getBoolean(com.android.internal.R.styleable.
360 TextAppearance_textAllCaps, false);
361 if (allCaps) {
362 mSwitchTransformationMethod = new AllCapsTransformationMethod(getContext());
363 mSwitchTransformationMethod.setLengthChangesAllowed(true);
364 } else {
365 mSwitchTransformationMethod = null;
366 }
367
Adam Powell12190b32010-11-28 19:07:53 -0800368 appearance.recycle();
369 }
370
371 private void setSwitchTypefaceByIndex(int typefaceIndex, int styleIndex) {
372 Typeface tf = null;
373 switch (typefaceIndex) {
374 case SANS:
375 tf = Typeface.SANS_SERIF;
376 break;
377
378 case SERIF:
379 tf = Typeface.SERIF;
380 break;
381
382 case MONOSPACE:
383 tf = Typeface.MONOSPACE;
384 break;
385 }
386
387 setSwitchTypeface(tf, styleIndex);
388 }
389
390 /**
391 * Sets the typeface and style in which the text should be displayed on the
392 * switch, and turns on the fake bold and italic bits in the Paint if the
393 * Typeface that you provided does not have all the bits in the
394 * style that you specified.
395 */
396 public void setSwitchTypeface(Typeface tf, int style) {
397 if (style > 0) {
398 if (tf == null) {
399 tf = Typeface.defaultFromStyle(style);
400 } else {
401 tf = Typeface.create(tf, style);
402 }
403
404 setSwitchTypeface(tf);
405 // now compute what (if any) algorithmic styling is needed
406 int typefaceStyle = tf != null ? tf.getStyle() : 0;
407 int need = style & ~typefaceStyle;
408 mTextPaint.setFakeBoldText((need & Typeface.BOLD) != 0);
409 mTextPaint.setTextSkewX((need & Typeface.ITALIC) != 0 ? -0.25f : 0);
410 } else {
Victoria Leaseaa0980a2012-06-11 14:46:04 -0700411 mTextPaint.setFakeBoldText(false);
Adam Powell12190b32010-11-28 19:07:53 -0800412 mTextPaint.setTextSkewX(0);
413 setSwitchTypeface(tf);
414 }
415 }
416
417 /**
Chet Haase150176d2011-08-26 09:54:06 -0700418 * Sets the typeface in which the text should be displayed on the switch.
Adam Powell12190b32010-11-28 19:07:53 -0800419 * Note that not all Typeface families actually have bold and italic
420 * variants, so you may need to use
421 * {@link #setSwitchTypeface(Typeface, int)} to get the appearance
422 * that you actually want.
423 *
424 * @attr ref android.R.styleable#TextView_typeface
425 * @attr ref android.R.styleable#TextView_textStyle
426 */
427 public void setSwitchTypeface(Typeface tf) {
428 if (mTextPaint.getTypeface() != tf) {
429 mTextPaint.setTypeface(tf);
430
431 requestLayout();
432 invalidate();
433 }
434 }
435
436 /**
Adam Powell6c86e1b2012-03-08 15:11:46 -0800437 * Set the amount of horizontal padding between the switch and the associated text.
438 *
439 * @param pixels Amount of padding in pixels
440 *
441 * @attr ref android.R.styleable#Switch_switchPadding
442 */
443 public void setSwitchPadding(int pixels) {
444 mSwitchPadding = pixels;
445 requestLayout();
446 }
447
448 /**
449 * Get the amount of horizontal padding between the switch and the associated text.
450 *
451 * @return Amount of padding in pixels
452 *
453 * @attr ref android.R.styleable#Switch_switchPadding
454 */
Ashley Rose55f9f922019-01-28 19:29:36 -0500455 @InspectableProperty
Adam Powell6c86e1b2012-03-08 15:11:46 -0800456 public int getSwitchPadding() {
457 return mSwitchPadding;
458 }
459
460 /**
461 * Set the minimum width of the switch in pixels. The switch's width will be the maximum
462 * of this value and its measured width as determined by the switch drawables and text used.
463 *
464 * @param pixels Minimum width of the switch in pixels
465 *
466 * @attr ref android.R.styleable#Switch_switchMinWidth
467 */
468 public void setSwitchMinWidth(int pixels) {
469 mSwitchMinWidth = pixels;
470 requestLayout();
471 }
472
473 /**
474 * Get the minimum width of the switch in pixels. The switch's width will be the maximum
475 * of this value and its measured width as determined by the switch drawables and text used.
476 *
477 * @return Minimum width of the switch in pixels
478 *
479 * @attr ref android.R.styleable#Switch_switchMinWidth
480 */
Ashley Rose55f9f922019-01-28 19:29:36 -0500481 @InspectableProperty
Adam Powell6c86e1b2012-03-08 15:11:46 -0800482 public int getSwitchMinWidth() {
483 return mSwitchMinWidth;
484 }
485
486 /**
487 * Set the horizontal padding around the text drawn on the switch itself.
488 *
489 * @param pixels Horizontal padding for switch thumb text in pixels
490 *
491 * @attr ref android.R.styleable#Switch_thumbTextPadding
492 */
493 public void setThumbTextPadding(int pixels) {
494 mThumbTextPadding = pixels;
495 requestLayout();
496 }
497
498 /**
499 * Get the horizontal padding around the text drawn on the switch itself.
500 *
501 * @return Horizontal padding for switch thumb text in pixels
502 *
503 * @attr ref android.R.styleable#Switch_thumbTextPadding
504 */
Ashley Rose55f9f922019-01-28 19:29:36 -0500505 @InspectableProperty
Adam Powell6c86e1b2012-03-08 15:11:46 -0800506 public int getThumbTextPadding() {
507 return mThumbTextPadding;
508 }
509
510 /**
511 * Set the drawable used for the track that the switch slides within.
512 *
513 * @param track Track drawable
514 *
515 * @attr ref android.R.styleable#Switch_track
516 */
517 public void setTrackDrawable(Drawable track) {
Alan Viveretteb0674052014-09-26 16:12:16 -0700518 if (mTrackDrawable != null) {
519 mTrackDrawable.setCallback(null);
520 }
Adam Powell6c86e1b2012-03-08 15:11:46 -0800521 mTrackDrawable = track;
Alan Viveretteb0674052014-09-26 16:12:16 -0700522 if (track != null) {
523 track.setCallback(this);
524 }
Adam Powell6c86e1b2012-03-08 15:11:46 -0800525 requestLayout();
526 }
527
528 /**
Adam Powelld9c7be62012-03-08 19:43:43 -0800529 * Set the drawable used for the track that the switch slides within.
530 *
Adam Powelldca510e2012-03-08 20:06:39 -0800531 * @param resId Resource ID of a track drawable
Adam Powelld9c7be62012-03-08 19:43:43 -0800532 *
533 * @attr ref android.R.styleable#Switch_track
534 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700535 public void setTrackResource(@DrawableRes int resId) {
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800536 setTrackDrawable(getContext().getDrawable(resId));
Adam Powelld9c7be62012-03-08 19:43:43 -0800537 }
538
539 /**
Adam Powell6c86e1b2012-03-08 15:11:46 -0800540 * Get the drawable used for the track that the switch slides within.
541 *
542 * @return Track drawable
543 *
544 * @attr ref android.R.styleable#Switch_track
545 */
Ashley Rose55f9f922019-01-28 19:29:36 -0500546 @InspectableProperty(name = "track")
Adam Powell6c86e1b2012-03-08 15:11:46 -0800547 public Drawable getTrackDrawable() {
548 return mTrackDrawable;
549 }
550
551 /**
Alan Viverettee7eee642015-01-29 14:27:49 -0800552 * Applies a tint to the track drawable. Does not modify the current
553 * tint mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
554 * <p>
555 * Subsequent calls to {@link #setTrackDrawable(Drawable)} will
556 * automatically mutate the drawable and apply the specified tint and tint
557 * mode using {@link Drawable#setTintList(ColorStateList)}.
558 *
559 * @param tint the tint to apply, may be {@code null} to clear tint
560 *
561 * @attr ref android.R.styleable#Switch_trackTint
562 * @see #getTrackTintList()
563 * @see Drawable#setTintList(ColorStateList)
564 */
565 public void setTrackTintList(@Nullable ColorStateList tint) {
566 mTrackTintList = tint;
567 mHasTrackTint = true;
568
569 applyTrackTint();
570 }
571
572 /**
573 * @return the tint applied to the track drawable
574 * @attr ref android.R.styleable#Switch_trackTint
575 * @see #setTrackTintList(ColorStateList)
576 */
Ashley Rose55f9f922019-01-28 19:29:36 -0500577 @InspectableProperty(name = "trackTint")
Alan Viverettee7eee642015-01-29 14:27:49 -0800578 @Nullable
579 public ColorStateList getTrackTintList() {
580 return mTrackTintList;
581 }
582
583 /**
584 * Specifies the blending mode used to apply the tint specified by
585 * {@link #setTrackTintList(ColorStateList)}} to the track drawable.
586 * The default mode is {@link PorterDuff.Mode#SRC_IN}.
587 *
588 * @param tintMode the blending mode used to apply the tint, may be
589 * {@code null} to clear tint
590 * @attr ref android.R.styleable#Switch_trackTintMode
591 * @see #getTrackTintMode()
592 * @see Drawable#setTintMode(PorterDuff.Mode)
593 */
594 public void setTrackTintMode(@Nullable PorterDuff.Mode tintMode) {
Nader Jawad8e31c3e2019-04-14 21:58:04 -0700595 setTrackTintBlendMode(tintMode != null ? BlendMode.fromValue(tintMode.nativeInt) : null);
596 }
597
598 /**
599 * Specifies the blending mode used to apply the tint specified by
600 * {@link #setTrackTintList(ColorStateList)}} to the track drawable.
601 * The default mode is {@link BlendMode#SRC_IN}.
602 *
603 * @param blendMode the blending mode used to apply the tint, may be
604 * {@code null} to clear tint
605 * @attr ref android.R.styleable#Switch_trackTintMode
606 * @see #getTrackTintMode()
607 * @see Drawable#setTintBlendMode(BlendMode)
608 */
609 public void setTrackTintBlendMode(@Nullable BlendMode blendMode) {
610 mTrackBlendMode = blendMode;
Alan Viverettee7eee642015-01-29 14:27:49 -0800611 mHasTrackTintMode = true;
612
613 applyTrackTint();
614 }
615
616 /**
617 * @return the blending mode used to apply the tint to the track
618 * drawable
619 * @attr ref android.R.styleable#Switch_trackTintMode
620 * @see #setTrackTintMode(PorterDuff.Mode)
621 */
Ashley Rose55f9f922019-01-28 19:29:36 -0500622 @InspectableProperty
Alan Viverettee7eee642015-01-29 14:27:49 -0800623 @Nullable
624 public PorterDuff.Mode getTrackTintMode() {
Nader Jawad8e31c3e2019-04-14 21:58:04 -0700625 BlendMode mode = getTrackTintBlendMode();
626 return mode != null ? BlendMode.blendModeToPorterDuffMode(mode) : null;
627 }
628
629 /**
630 * @return the blending mode used to apply the tint to the track
631 * drawable
632 * @attr ref android.R.styleable#Switch_trackTintMode
633 * @see #setTrackTintBlendMode(BlendMode)
634 */
635 @InspectableProperty(attributeId = com.android.internal.R.styleable.Switch_trackTintMode)
636 @Nullable
637 public BlendMode getTrackTintBlendMode() {
638 return mTrackBlendMode;
Alan Viverettee7eee642015-01-29 14:27:49 -0800639 }
640
641 private void applyTrackTint() {
642 if (mTrackDrawable != null && (mHasTrackTint || mHasTrackTintMode)) {
643 mTrackDrawable = mTrackDrawable.mutate();
644
645 if (mHasTrackTint) {
646 mTrackDrawable.setTintList(mTrackTintList);
647 }
648
649 if (mHasTrackTintMode) {
Nader Jawad8e31c3e2019-04-14 21:58:04 -0700650 mTrackDrawable.setTintBlendMode(mTrackBlendMode);
Alan Viverettee7eee642015-01-29 14:27:49 -0800651 }
652
653 // The drawable (or one of its children) may not have been
654 // stateful before applying the tint, so let's try again.
655 if (mTrackDrawable.isStateful()) {
656 mTrackDrawable.setState(getDrawableState());
657 }
658 }
659 }
660
661 /**
Adam Powell6c86e1b2012-03-08 15:11:46 -0800662 * Set the drawable used for the switch "thumb" - the piece that the user
663 * can physically touch and drag along the track.
664 *
665 * @param thumb Thumb drawable
666 *
667 * @attr ref android.R.styleable#Switch_thumb
668 */
669 public void setThumbDrawable(Drawable thumb) {
Alan Viveretteb0674052014-09-26 16:12:16 -0700670 if (mThumbDrawable != null) {
671 mThumbDrawable.setCallback(null);
672 }
Adam Powell6c86e1b2012-03-08 15:11:46 -0800673 mThumbDrawable = thumb;
Alan Viveretteb0674052014-09-26 16:12:16 -0700674 if (thumb != null) {
675 thumb.setCallback(this);
676 }
Adam Powell6c86e1b2012-03-08 15:11:46 -0800677 requestLayout();
678 }
679
680 /**
Adam Powelld9c7be62012-03-08 19:43:43 -0800681 * Set the drawable used for the switch "thumb" - the piece that the user
682 * can physically touch and drag along the track.
683 *
Adam Powelldca510e2012-03-08 20:06:39 -0800684 * @param resId Resource ID of a thumb drawable
Adam Powelld9c7be62012-03-08 19:43:43 -0800685 *
686 * @attr ref android.R.styleable#Switch_thumb
687 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700688 public void setThumbResource(@DrawableRes int resId) {
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800689 setThumbDrawable(getContext().getDrawable(resId));
Adam Powelld9c7be62012-03-08 19:43:43 -0800690 }
691
692 /**
Adam Powell6c86e1b2012-03-08 15:11:46 -0800693 * Get the drawable used for the switch "thumb" - the piece that the user
694 * can physically touch and drag along the track.
695 *
696 * @return Thumb drawable
697 *
698 * @attr ref android.R.styleable#Switch_thumb
699 */
Ashley Rose55f9f922019-01-28 19:29:36 -0500700 @InspectableProperty(name = "thumb")
Adam Powell6c86e1b2012-03-08 15:11:46 -0800701 public Drawable getThumbDrawable() {
702 return mThumbDrawable;
703 }
704
705 /**
Alan Viverettee7eee642015-01-29 14:27:49 -0800706 * Applies a tint to the thumb drawable. Does not modify the current
707 * tint mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
708 * <p>
709 * Subsequent calls to {@link #setThumbDrawable(Drawable)} will
710 * automatically mutate the drawable and apply the specified tint and tint
711 * mode using {@link Drawable#setTintList(ColorStateList)}.
712 *
713 * @param tint the tint to apply, may be {@code null} to clear tint
714 *
715 * @attr ref android.R.styleable#Switch_thumbTint
716 * @see #getThumbTintList()
717 * @see Drawable#setTintList(ColorStateList)
718 */
719 public void setThumbTintList(@Nullable ColorStateList tint) {
720 mThumbTintList = tint;
721 mHasThumbTint = true;
722
723 applyThumbTint();
724 }
725
726 /**
727 * @return the tint applied to the thumb drawable
728 * @attr ref android.R.styleable#Switch_thumbTint
729 * @see #setThumbTintList(ColorStateList)
730 */
Ashley Rose55f9f922019-01-28 19:29:36 -0500731 @InspectableProperty(name = "thumbTint")
Alan Viverettee7eee642015-01-29 14:27:49 -0800732 @Nullable
733 public ColorStateList getThumbTintList() {
734 return mThumbTintList;
735 }
736
737 /**
738 * Specifies the blending mode used to apply the tint specified by
739 * {@link #setThumbTintList(ColorStateList)}} to the thumb drawable.
740 * The default mode is {@link PorterDuff.Mode#SRC_IN}.
741 *
742 * @param tintMode the blending mode used to apply the tint, may be
743 * {@code null} to clear tint
744 * @attr ref android.R.styleable#Switch_thumbTintMode
745 * @see #getThumbTintMode()
746 * @see Drawable#setTintMode(PorterDuff.Mode)
747 */
748 public void setThumbTintMode(@Nullable PorterDuff.Mode tintMode) {
Nader Jawad8e31c3e2019-04-14 21:58:04 -0700749 setThumbTintBlendMode(tintMode != null ? BlendMode.fromValue(tintMode.nativeInt) : null);
750 }
751
752 /**
753 * Specifies the blending mode used to apply the tint specified by
754 * {@link #setThumbTintList(ColorStateList)}} to the thumb drawable.
755 * The default mode is {@link PorterDuff.Mode#SRC_IN}.
756 *
757 * @param blendMode the blending mode used to apply the tint, may be
758 * {@code null} to clear tint
759 * @attr ref android.R.styleable#Switch_thumbTintMode
760 * @see #getThumbTintMode()
761 * @see Drawable#setTintBlendMode(BlendMode)
762 */
763 public void setThumbTintBlendMode(@Nullable BlendMode blendMode) {
764 mThumbBlendMode = blendMode;
Alan Viverettee7eee642015-01-29 14:27:49 -0800765 mHasThumbTintMode = true;
766
767 applyThumbTint();
768 }
769
770 /**
771 * @return the blending mode used to apply the tint to the thumb
772 * drawable
773 * @attr ref android.R.styleable#Switch_thumbTintMode
774 * @see #setThumbTintMode(PorterDuff.Mode)
775 */
Ashley Rose55f9f922019-01-28 19:29:36 -0500776 @InspectableProperty
Alan Viverettee7eee642015-01-29 14:27:49 -0800777 @Nullable
778 public PorterDuff.Mode getThumbTintMode() {
Nader Jawad8e31c3e2019-04-14 21:58:04 -0700779 BlendMode mode = getThumbTintBlendMode();
780 return mode != null ? BlendMode.blendModeToPorterDuffMode(mode) : null;
781 }
782
783 /**
784 * @return the blending mode used to apply the tint to the thumb
785 * drawable
786 * @attr ref android.R.styleable#Switch_thumbTintMode
787 * @see #setThumbTintBlendMode(BlendMode)
788 */
789 @InspectableProperty(attributeId = com.android.internal.R.styleable.Switch_thumbTintMode)
790 @Nullable
791 public BlendMode getThumbTintBlendMode() {
792 return mThumbBlendMode;
Alan Viverettee7eee642015-01-29 14:27:49 -0800793 }
794
795 private void applyThumbTint() {
796 if (mThumbDrawable != null && (mHasThumbTint || mHasThumbTintMode)) {
797 mThumbDrawable = mThumbDrawable.mutate();
798
799 if (mHasThumbTint) {
800 mThumbDrawable.setTintList(mThumbTintList);
801 }
802
803 if (mHasThumbTintMode) {
Nader Jawad8e31c3e2019-04-14 21:58:04 -0700804 mThumbDrawable.setTintBlendMode(mThumbBlendMode);
Alan Viverettee7eee642015-01-29 14:27:49 -0800805 }
806
807 // The drawable (or one of its children) may not have been
808 // stateful before applying the tint, so let's try again.
809 if (mThumbDrawable.isStateful()) {
810 mThumbDrawable.setState(getDrawableState());
811 }
812 }
813 }
814
815 /**
Alan Viverette661e6362014-05-12 10:55:37 -0700816 * Specifies whether the track should be split by the thumb. When true,
817 * the thumb's optical bounds will be clipped out of the track drawable,
818 * then the thumb will be drawn into the resulting gap.
819 *
820 * @param splitTrack Whether the track should be split by the thumb
821 *
822 * @attr ref android.R.styleable#Switch_splitTrack
823 */
824 public void setSplitTrack(boolean splitTrack) {
825 mSplitTrack = splitTrack;
826 invalidate();
827 }
828
829 /**
830 * Returns whether the track should be split by the thumb.
831 *
832 * @attr ref android.R.styleable#Switch_splitTrack
833 */
Ashley Rose55f9f922019-01-28 19:29:36 -0500834 @InspectableProperty
Alan Viverette661e6362014-05-12 10:55:37 -0700835 public boolean getSplitTrack() {
836 return mSplitTrack;
837 }
838
839 /**
Chet Haase150176d2011-08-26 09:54:06 -0700840 * Returns the text displayed when the button is in the checked state.
Adam Powell6c86e1b2012-03-08 15:11:46 -0800841 *
842 * @attr ref android.R.styleable#Switch_textOn
Adam Powell12190b32010-11-28 19:07:53 -0800843 */
Ashley Rose55f9f922019-01-28 19:29:36 -0500844 @InspectableProperty
Adam Powell12190b32010-11-28 19:07:53 -0800845 public CharSequence getTextOn() {
846 return mTextOn;
847 }
848
849 /**
Chet Haase150176d2011-08-26 09:54:06 -0700850 * Sets the text displayed when the button is in the checked state.
Adam Powell6c86e1b2012-03-08 15:11:46 -0800851 *
852 * @attr ref android.R.styleable#Switch_textOn
Adam Powell12190b32010-11-28 19:07:53 -0800853 */
854 public void setTextOn(CharSequence textOn) {
855 mTextOn = textOn;
856 requestLayout();
yingleiw473fc122019-10-11 15:10:55 -0700857 // Default state is derived from on/off-text, so state has to be updated when on/off-text
858 // are updated.
859 setDefaultStateDescritption();
Adam Powell12190b32010-11-28 19:07:53 -0800860 }
861
862 /**
Chet Haase150176d2011-08-26 09:54:06 -0700863 * Returns the text displayed when the button is not in the checked state.
Adam Powell6c86e1b2012-03-08 15:11:46 -0800864 *
865 * @attr ref android.R.styleable#Switch_textOff
Adam Powell12190b32010-11-28 19:07:53 -0800866 */
Ashley Rose55f9f922019-01-28 19:29:36 -0500867 @InspectableProperty
Adam Powell12190b32010-11-28 19:07:53 -0800868 public CharSequence getTextOff() {
869 return mTextOff;
870 }
871
872 /**
Chet Haase150176d2011-08-26 09:54:06 -0700873 * Sets the text displayed when the button is not in the checked state.
Adam Powell6c86e1b2012-03-08 15:11:46 -0800874 *
875 * @attr ref android.R.styleable#Switch_textOff
Adam Powell12190b32010-11-28 19:07:53 -0800876 */
877 public void setTextOff(CharSequence textOff) {
878 mTextOff = textOff;
879 requestLayout();
yingleiw473fc122019-10-11 15:10:55 -0700880 // Default state is derived from on/off-text, so state has to be updated when on/off-text
881 // are updated.
882 setDefaultStateDescritption();
Adam Powell12190b32010-11-28 19:07:53 -0800883 }
884
Alan Viverette2a37cf8d2014-06-19 17:09:10 -0700885 /**
886 * Sets whether the on/off text should be displayed.
887 *
888 * @param showText {@code true} to display on/off text
Alan Viverette0c0dde72014-07-30 13:29:39 -0700889 * @attr ref android.R.styleable#Switch_showText
Alan Viverette2a37cf8d2014-06-19 17:09:10 -0700890 */
891 public void setShowText(boolean showText) {
892 if (mShowText != showText) {
893 mShowText = showText;
894 requestLayout();
895 }
896 }
897
898 /**
899 * @return whether the on/off text should be displayed
Alan Viverette0c0dde72014-07-30 13:29:39 -0700900 * @attr ref android.R.styleable#Switch_showText
Alan Viverette2a37cf8d2014-06-19 17:09:10 -0700901 */
Ashley Rose55f9f922019-01-28 19:29:36 -0500902 @InspectableProperty
Alan Viverette2a37cf8d2014-06-19 17:09:10 -0700903 public boolean getShowText() {
904 return mShowText;
905 }
906
Adam Powell12190b32010-11-28 19:07:53 -0800907 @Override
908 public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Alan Viverette2a37cf8d2014-06-19 17:09:10 -0700909 if (mShowText) {
910 if (mOnLayout == null) {
911 mOnLayout = makeLayout(mTextOn);
912 }
Alan Viverette5876ff42014-03-03 17:40:46 -0800913
Alan Viverette2a37cf8d2014-06-19 17:09:10 -0700914 if (mOffLayout == null) {
915 mOffLayout = makeLayout(mTextOff);
916 }
Adam Powell12190b32010-11-28 19:07:53 -0800917 }
918
Alan Viverette9b38f6c2014-07-30 02:39:07 +0000919 final Rect padding = mTempRect;
Alan Viverette0c0dde72014-07-30 13:29:39 -0700920 final int thumbWidth;
921 final int thumbHeight;
922 if (mThumbDrawable != null) {
923 // Cached thumb width does not include padding.
924 mThumbDrawable.getPadding(padding);
925 thumbWidth = mThumbDrawable.getIntrinsicWidth() - padding.left - padding.right;
926 thumbHeight = mThumbDrawable.getIntrinsicHeight();
927 } else {
928 thumbWidth = 0;
929 thumbHeight = 0;
930 }
931
932 final int maxTextWidth;
933 if (mShowText) {
934 maxTextWidth = Math.max(mOnLayout.getWidth(), mOffLayout.getWidth())
935 + mThumbTextPadding * 2;
936 } else {
937 maxTextWidth = 0;
938 }
939
940 mThumbWidth = Math.max(maxTextWidth, thumbWidth);
941
942 final int trackHeight;
Alan Viverette4d065a02014-07-11 15:28:38 -0700943 if (mTrackDrawable != null) {
944 mTrackDrawable.getPadding(padding);
945 trackHeight = mTrackDrawable.getIntrinsicHeight();
946 } else {
947 padding.setEmpty();
948 trackHeight = 0;
949 }
950
Alan Viverette0c0dde72014-07-30 13:29:39 -0700951 // Adjust left and right padding to ensure there's enough room for the
952 // thumb's padding (when present).
953 int paddingLeft = padding.left;
954 int paddingRight = padding.right;
Alan Viverette4d065a02014-07-11 15:28:38 -0700955 if (mThumbDrawable != null) {
Alan Viverette0c0dde72014-07-30 13:29:39 -0700956 final Insets inset = mThumbDrawable.getOpticalInsets();
957 paddingLeft = Math.max(paddingLeft, inset.left);
958 paddingRight = Math.max(paddingRight, inset.right);
Alan Viverette4d065a02014-07-11 15:28:38 -0700959 }
Alan Viverette5876ff42014-03-03 17:40:46 -0800960
Adam Powell12190b32010-11-28 19:07:53 -0800961 final int switchWidth = Math.max(mSwitchMinWidth,
Alan Viverette0c0dde72014-07-30 13:29:39 -0700962 2 * mThumbWidth + paddingLeft + paddingRight);
Alan Viverette4d065a02014-07-11 15:28:38 -0700963 final int switchHeight = Math.max(trackHeight, thumbHeight);
Adam Powell12190b32010-11-28 19:07:53 -0800964 mSwitchWidth = switchWidth;
965 mSwitchHeight = switchHeight;
966
967 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
Alan Viverette4d065a02014-07-11 15:28:38 -0700968
Adam Powell12190b32010-11-28 19:07:53 -0800969 final int measuredHeight = getMeasuredHeight();
970 if (measuredHeight < switchHeight) {
Dianne Hackborn189ee182010-12-02 21:48:53 -0800971 setMeasuredDimension(getMeasuredWidthAndState(), switchHeight);
Adam Powell12190b32010-11-28 19:07:53 -0800972 }
973 }
974
Alan Viverettea54956a2015-01-07 16:05:02 -0800975 /** @hide */
Svetoslav Ganov63bce032011-07-23 19:52:17 -0700976 @Override
Alan Viverettea54956a2015-01-07 16:05:02 -0800977 public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
978 super.onPopulateAccessibilityEventInternal(event);
Alan Viverette2a37cf8d2014-06-19 17:09:10 -0700979
980 final CharSequence text = isChecked() ? mTextOn : mTextOff;
981 if (text != null) {
982 event.getText().add(text);
Svetoslav Ganov76502592011-07-29 10:44:59 -0700983 }
Svetoslav Ganov63bce032011-07-23 19:52:17 -0700984 }
985
Adam Powell12190b32010-11-28 19:07:53 -0800986 private Layout makeLayout(CharSequence text) {
Daniel Sandler4c3308d2012-04-19 11:04:39 -0400987 final CharSequence transformed = (mSwitchTransformationMethod != null)
988 ? mSwitchTransformationMethod.getTransformation(text, this)
989 : text;
990
Siyamed Sinir79bf9d12016-05-18 19:57:52 -0700991 int width = (int) Math.ceil(Layout.getDesiredWidth(transformed, 0,
992 transformed.length(), mTextPaint, getTextDirectionHeuristic()));
Roozbeh Pournader5caf5a62017-08-22 18:08:09 -0700993 return StaticLayout.Builder.obtain(transformed, 0, transformed.length(), mTextPaint, width)
994 .setUseLineSpacingFromFallbacks(mUseFallbackLineSpacing)
995 .build();
Adam Powell12190b32010-11-28 19:07:53 -0800996 }
997
998 /**
999 * @return true if (x, y) is within the target area of the switch thumb
1000 */
1001 private boolean hitThumb(float x, float y) {
Alan Viverette01a09632014-12-08 13:02:06 -08001002 if (mThumbDrawable == null) {
1003 return false;
1004 }
1005
Alan Viverettecc2688d2013-09-17 17:00:12 -07001006 // Relies on mTempRect, MUST be called first!
1007 final int thumbOffset = getThumbOffset();
1008
Adam Powell12190b32010-11-28 19:07:53 -08001009 mThumbDrawable.getPadding(mTempRect);
1010 final int thumbTop = mSwitchTop - mTouchSlop;
Alan Viverettecc2688d2013-09-17 17:00:12 -07001011 final int thumbLeft = mSwitchLeft + thumbOffset - mTouchSlop;
Adam Powell12190b32010-11-28 19:07:53 -08001012 final int thumbRight = thumbLeft + mThumbWidth +
1013 mTempRect.left + mTempRect.right + mTouchSlop;
1014 final int thumbBottom = mSwitchBottom + mTouchSlop;
1015 return x > thumbLeft && x < thumbRight && y > thumbTop && y < thumbBottom;
1016 }
1017
1018 @Override
1019 public boolean onTouchEvent(MotionEvent ev) {
1020 mVelocityTracker.addMovement(ev);
1021 final int action = ev.getActionMasked();
1022 switch (action) {
1023 case MotionEvent.ACTION_DOWN: {
1024 final float x = ev.getX();
1025 final float y = ev.getY();
Gilles Debunnec2ab0d62011-06-13 12:52:48 -07001026 if (isEnabled() && hitThumb(x, y)) {
Adam Powell12190b32010-11-28 19:07:53 -08001027 mTouchMode = TOUCH_MODE_DOWN;
1028 mTouchX = x;
1029 mTouchY = y;
1030 }
1031 break;
1032 }
1033
1034 case MotionEvent.ACTION_MOVE: {
1035 switch (mTouchMode) {
1036 case TOUCH_MODE_IDLE:
1037 // Didn't target the thumb, treat normally.
1038 break;
1039
1040 case TOUCH_MODE_DOWN: {
1041 final float x = ev.getX();
1042 final float y = ev.getY();
1043 if (Math.abs(x - mTouchX) > mTouchSlop ||
1044 Math.abs(y - mTouchY) > mTouchSlop) {
1045 mTouchMode = TOUCH_MODE_DRAGGING;
1046 getParent().requestDisallowInterceptTouchEvent(true);
1047 mTouchX = x;
1048 mTouchY = y;
1049 return true;
1050 }
1051 break;
1052 }
1053
1054 case TOUCH_MODE_DRAGGING: {
1055 final float x = ev.getX();
Alan Viverettecc2688d2013-09-17 17:00:12 -07001056 final int thumbScrollRange = getThumbScrollRange();
1057 final float thumbScrollOffset = x - mTouchX;
1058 float dPos;
1059 if (thumbScrollRange != 0) {
1060 dPos = thumbScrollOffset / thumbScrollRange;
1061 } else {
1062 // If the thumb scroll range is empty, just use the
1063 // movement direction to snap on or off.
1064 dPos = thumbScrollOffset > 0 ? 1 : -1;
1065 }
1066 if (isLayoutRtl()) {
1067 dPos = -dPos;
1068 }
1069 final float newPos = MathUtils.constrain(mThumbPosition + dPos, 0, 1);
Adam Powell12190b32010-11-28 19:07:53 -08001070 if (newPos != mThumbPosition) {
Adam Powell12190b32010-11-28 19:07:53 -08001071 mTouchX = x;
Alan Viverettecc2688d2013-09-17 17:00:12 -07001072 setThumbPosition(newPos);
Adam Powell12190b32010-11-28 19:07:53 -08001073 }
1074 return true;
1075 }
1076 }
1077 break;
1078 }
1079
1080 case MotionEvent.ACTION_UP:
1081 case MotionEvent.ACTION_CANCEL: {
1082 if (mTouchMode == TOUCH_MODE_DRAGGING) {
1083 stopDrag(ev);
Alan Viverettead2f8e32014-05-16 13:28:33 -07001084 // Allow super class to handle pressed state, etc.
1085 super.onTouchEvent(ev);
Adam Powell12190b32010-11-28 19:07:53 -08001086 return true;
1087 }
1088 mTouchMode = TOUCH_MODE_IDLE;
1089 mVelocityTracker.clear();
1090 break;
1091 }
1092 }
1093
1094 return super.onTouchEvent(ev);
1095 }
1096
1097 private void cancelSuperTouch(MotionEvent ev) {
1098 MotionEvent cancel = MotionEvent.obtain(ev);
1099 cancel.setAction(MotionEvent.ACTION_CANCEL);
1100 super.onTouchEvent(cancel);
1101 cancel.recycle();
1102 }
1103
1104 /**
1105 * Called from onTouchEvent to end a drag operation.
1106 *
1107 * @param ev Event that triggered the end of drag mode - ACTION_UP or ACTION_CANCEL
1108 */
1109 private void stopDrag(MotionEvent ev) {
1110 mTouchMode = TOUCH_MODE_IDLE;
Adam Powell12190b32010-11-28 19:07:53 -08001111
Alan Viverette86453ff2013-09-26 14:46:08 -07001112 // Commit the change if the event is up and not canceled and the switch
1113 // has not been disabled during the drag.
1114 final boolean commitChange = ev.getAction() == MotionEvent.ACTION_UP && isEnabled();
Alan Viveretted4e77902014-10-27 17:50:51 -07001115 final boolean oldState = isChecked();
Alan Viverette86453ff2013-09-26 14:46:08 -07001116 final boolean newState;
Adam Powell12190b32010-11-28 19:07:53 -08001117 if (commitChange) {
Adam Powell12190b32010-11-28 19:07:53 -08001118 mVelocityTracker.computeCurrentVelocity(1000);
Alan Viverette86453ff2013-09-26 14:46:08 -07001119 final float xvel = mVelocityTracker.getXVelocity();
Adam Powell12190b32010-11-28 19:07:53 -08001120 if (Math.abs(xvel) > mMinFlingVelocity) {
Fabrice Di Meglio28efba32012-06-01 16:52:31 -07001121 newState = isLayoutRtl() ? (xvel < 0) : (xvel > 0);
Adam Powell12190b32010-11-28 19:07:53 -08001122 } else {
1123 newState = getTargetCheckedState();
1124 }
Adam Powell12190b32010-11-28 19:07:53 -08001125 } else {
Alan Viveretted4e77902014-10-27 17:50:51 -07001126 newState = oldState;
Adam Powell12190b32010-11-28 19:07:53 -08001127 }
Alan Viverette86453ff2013-09-26 14:46:08 -07001128
Alan Viveretted4e77902014-10-27 17:50:51 -07001129 if (newState != oldState) {
1130 playSoundEffect(SoundEffectConstants.CLICK);
Alan Viveretted4e77902014-10-27 17:50:51 -07001131 }
Alan Viverette03306a02015-08-07 11:34:25 -04001132 // Always call setChecked so that the thumb is moved back to the correct edge
1133 setChecked(newState);
Alan Viverette86453ff2013-09-26 14:46:08 -07001134 cancelSuperTouch(ev);
Adam Powell12190b32010-11-28 19:07:53 -08001135 }
1136
1137 private void animateThumbToCheckedState(boolean newCheckedState) {
Alan Viverettecc2688d2013-09-17 17:00:12 -07001138 final float targetPosition = newCheckedState ? 1 : 0;
1139 mPositionAnimator = ObjectAnimator.ofFloat(this, THUMB_POS, targetPosition);
1140 mPositionAnimator.setDuration(THUMB_ANIMATION_DURATION);
1141 mPositionAnimator.setAutoCancel(true);
1142 mPositionAnimator.start();
1143 }
1144
Mathew Inwood978c6e22018-08-21 15:58:55 +01001145 @UnsupportedAppUsage
Alan Viverettecc2688d2013-09-17 17:00:12 -07001146 private void cancelPositionAnimator() {
1147 if (mPositionAnimator != null) {
1148 mPositionAnimator.cancel();
1149 }
Adam Powell12190b32010-11-28 19:07:53 -08001150 }
1151
1152 private boolean getTargetCheckedState() {
Alan Viverettecc2688d2013-09-17 17:00:12 -07001153 return mThumbPosition > 0.5f;
Fabrice Di Meglio28efba32012-06-01 16:52:31 -07001154 }
1155
Alan Viverettecc2688d2013-09-17 17:00:12 -07001156 /**
1157 * Sets the thumb position as a decimal value between 0 (off) and 1 (on).
1158 *
1159 * @param position new position between [0,1]
1160 */
Mathew Inwood978c6e22018-08-21 15:58:55 +01001161 @UnsupportedAppUsage
Alan Viverettecc2688d2013-09-17 17:00:12 -07001162 private void setThumbPosition(float position) {
1163 mThumbPosition = position;
1164 invalidate();
1165 }
1166
1167 @Override
1168 public void toggle() {
Alan Viverette86453ff2013-09-26 14:46:08 -07001169 setChecked(!isChecked());
Adam Powell12190b32010-11-28 19:07:53 -08001170 }
1171
yingleiw473fc122019-10-11 15:10:55 -07001172 /** @hide **/
1173 @Override
1174 @NonNull
1175 protected CharSequence getButtonStateDescription() {
1176 if (isChecked()) {
1177 return mTextOn == null ? getResources().getString(R.string.capital_on) : mTextOn;
1178 } else {
1179 return mTextOff == null ? getResources().getString(R.string.capital_off) : mTextOff;
1180 }
1181 }
1182
Adam Powell12190b32010-11-28 19:07:53 -08001183 @Override
1184 public void setChecked(boolean checked) {
1185 super.setChecked(checked);
Alan Viverettecc2688d2013-09-17 17:00:12 -07001186
Alan Viverette467d6292014-08-12 15:13:19 -07001187 // Calling the super method may result in setChecked() getting called
1188 // recursively with a different value, so load the REAL value...
1189 checked = isChecked();
1190
Alan Viverette86453ff2013-09-26 14:46:08 -07001191 if (isAttachedToWindow() && isLaidOut()) {
1192 animateThumbToCheckedState(checked);
1193 } else {
1194 // Immediately move the thumb to the new position.
1195 cancelPositionAnimator();
1196 setThumbPosition(checked ? 1 : 0);
1197 }
Adam Powell12190b32010-11-28 19:07:53 -08001198 }
1199
1200 @Override
1201 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
1202 super.onLayout(changed, left, top, right, bottom);
1203
Alan Viverette0c0dde72014-07-30 13:29:39 -07001204 int opticalInsetLeft = 0;
1205 int opticalInsetRight = 0;
1206 if (mThumbDrawable != null) {
1207 final Rect trackPadding = mTempRect;
1208 if (mTrackDrawable != null) {
1209 mTrackDrawable.getPadding(trackPadding);
1210 } else {
1211 trackPadding.setEmpty();
1212 }
Fabrice Di Meglio28efba32012-06-01 16:52:31 -07001213
Alan Viverette0c0dde72014-07-30 13:29:39 -07001214 final Insets insets = mThumbDrawable.getOpticalInsets();
1215 opticalInsetLeft = Math.max(0, insets.left - trackPadding.left);
1216 opticalInsetRight = Math.max(0, insets.right - trackPadding.right);
Alan Viverette8bb39902014-07-29 17:22:30 -07001217 }
1218
Alan Viverette0c0dde72014-07-30 13:29:39 -07001219 final int switchRight;
1220 final int switchLeft;
1221 if (isLayoutRtl()) {
1222 switchLeft = getPaddingLeft() + opticalInsetLeft;
1223 switchRight = switchLeft + mSwitchWidth - opticalInsetLeft - opticalInsetRight;
1224 } else {
1225 switchRight = getWidth() - getPaddingRight() - opticalInsetRight;
1226 switchLeft = switchRight - mSwitchWidth + opticalInsetLeft + opticalInsetRight;
1227 }
1228
1229 final int switchTop;
1230 final int switchBottom;
Adam Powell12190b32010-11-28 19:07:53 -08001231 switch (getGravity() & Gravity.VERTICAL_GRAVITY_MASK) {
1232 default:
1233 case Gravity.TOP:
1234 switchTop = getPaddingTop();
1235 switchBottom = switchTop + mSwitchHeight;
1236 break;
1237
1238 case Gravity.CENTER_VERTICAL:
1239 switchTop = (getPaddingTop() + getHeight() - getPaddingBottom()) / 2 -
1240 mSwitchHeight / 2;
1241 switchBottom = switchTop + mSwitchHeight;
1242 break;
1243
1244 case Gravity.BOTTOM:
1245 switchBottom = getHeight() - getPaddingBottom();
1246 switchTop = switchBottom - mSwitchHeight;
1247 break;
1248 }
1249
1250 mSwitchLeft = switchLeft;
1251 mSwitchTop = switchTop;
1252 mSwitchBottom = switchBottom;
1253 mSwitchRight = switchRight;
1254 }
1255
1256 @Override
Alan Viverettead2f8e32014-05-16 13:28:33 -07001257 public void draw(Canvas c) {
Alan Viverette4d065a02014-07-11 15:28:38 -07001258 final Rect padding = mTempRect;
Alan Viverette5876ff42014-03-03 17:40:46 -08001259 final int switchLeft = mSwitchLeft;
1260 final int switchTop = mSwitchTop;
1261 final int switchRight = mSwitchRight;
1262 final int switchBottom = mSwitchBottom;
Alan Viverette0c0dde72014-07-30 13:29:39 -07001263
1264 int thumbInitialLeft = switchLeft + getThumbOffset();
1265
1266 final Insets thumbInsets;
1267 if (mThumbDrawable != null) {
1268 thumbInsets = mThumbDrawable.getOpticalInsets();
1269 } else {
1270 thumbInsets = Insets.NONE;
Alan Viverette8bb39902014-07-29 17:22:30 -07001271 }
Alan Viverettecc2688d2013-09-17 17:00:12 -07001272
Alan Viverette0c0dde72014-07-30 13:29:39 -07001273 // Layout the track.
1274 if (mTrackDrawable != null) {
1275 mTrackDrawable.getPadding(padding);
Alan Viverette9b38f6c2014-07-30 02:39:07 +00001276
Alan Viverette0c0dde72014-07-30 13:29:39 -07001277 // Adjust thumb position for track padding.
1278 thumbInitialLeft += padding.left;
1279
1280 // If necessary, offset by the optical insets of the thumb asset.
1281 int trackLeft = switchLeft;
1282 int trackTop = switchTop;
1283 int trackRight = switchRight;
1284 int trackBottom = switchBottom;
1285 if (thumbInsets != Insets.NONE) {
1286 if (thumbInsets.left > padding.left) {
1287 trackLeft += thumbInsets.left - padding.left;
1288 }
1289 if (thumbInsets.top > padding.top) {
1290 trackTop += thumbInsets.top - padding.top;
1291 }
1292 if (thumbInsets.right > padding.right) {
1293 trackRight -= thumbInsets.right - padding.right;
1294 }
1295 if (thumbInsets.bottom > padding.bottom) {
1296 trackBottom -= thumbInsets.bottom - padding.bottom;
1297 }
1298 }
1299 mTrackDrawable.setBounds(trackLeft, trackTop, trackRight, trackBottom);
1300 }
Alan Viverette9b38f6c2014-07-30 02:39:07 +00001301
Alan Viverette661e6362014-05-12 10:55:37 -07001302 // Layout the thumb.
Alan Viverette4d065a02014-07-11 15:28:38 -07001303 if (mThumbDrawable != null) {
1304 mThumbDrawable.getPadding(padding);
Alan Viverette0c0dde72014-07-30 13:29:39 -07001305
1306 final int thumbLeft = thumbInitialLeft - padding.left;
1307 final int thumbRight = thumbInitialLeft + mThumbWidth + padding.right;
Alan Viverette4d065a02014-07-11 15:28:38 -07001308 mThumbDrawable.setBounds(thumbLeft, switchTop, thumbRight, switchBottom);
Alan Viverette61956602014-04-22 19:07:06 -07001309
Alan Viverette4d065a02014-07-11 15:28:38 -07001310 final Drawable background = getBackground();
1311 if (background != null) {
1312 background.setHotspotBounds(thumbLeft, switchTop, thumbRight, switchBottom);
1313 }
Alan Viverette61956602014-04-22 19:07:06 -07001314 }
1315
Alan Viverettead2f8e32014-05-16 13:28:33 -07001316 // Draw the background.
1317 super.draw(c);
1318 }
1319
1320 @Override
1321 protected void onDraw(Canvas canvas) {
Alan Viverette61956602014-04-22 19:07:06 -07001322 super.onDraw(canvas);
1323
Alan Viverette4d065a02014-07-11 15:28:38 -07001324 final Rect padding = mTempRect;
Alan Viverettead2f8e32014-05-16 13:28:33 -07001325 final Drawable trackDrawable = mTrackDrawable;
Alan Viverette4d065a02014-07-11 15:28:38 -07001326 if (trackDrawable != null) {
1327 trackDrawable.getPadding(padding);
1328 } else {
1329 padding.setEmpty();
1330 }
Alan Viverettead2f8e32014-05-16 13:28:33 -07001331
1332 final int switchTop = mSwitchTop;
1333 final int switchBottom = mSwitchBottom;
Alan Viverette4d065a02014-07-11 15:28:38 -07001334 final int switchInnerTop = switchTop + padding.top;
Alan Viverette4d065a02014-07-11 15:28:38 -07001335 final int switchInnerBottom = switchBottom - padding.bottom;
Alan Viverettead2f8e32014-05-16 13:28:33 -07001336
Alan Viverette4d065a02014-07-11 15:28:38 -07001337 final Drawable thumbDrawable = mThumbDrawable;
1338 if (trackDrawable != null) {
1339 if (mSplitTrack && thumbDrawable != null) {
1340 final Insets insets = thumbDrawable.getOpticalInsets();
1341 thumbDrawable.copyBounds(padding);
1342 padding.left += insets.left;
1343 padding.right -= insets.right;
Alan Viverette661e6362014-05-12 10:55:37 -07001344
Alan Viverette4d065a02014-07-11 15:28:38 -07001345 final int saveCount = canvas.save();
1346 canvas.clipRect(padding, Op.DIFFERENCE);
1347 trackDrawable.draw(canvas);
1348 canvas.restoreToCount(saveCount);
1349 } else {
1350 trackDrawable.draw(canvas);
1351 }
Alan Viverette661e6362014-05-12 10:55:37 -07001352 }
Alan Viverette61956602014-04-22 19:07:06 -07001353
1354 final int saveCount = canvas.save();
Alan Viverette4d065a02014-07-11 15:28:38 -07001355
1356 if (thumbDrawable != null) {
Alan Viverette4d065a02014-07-11 15:28:38 -07001357 thumbDrawable.draw(canvas);
1358 }
Adam Powell12190b32010-11-28 19:07:53 -08001359
Alan Viverette5876ff42014-03-03 17:40:46 -08001360 final Layout switchText = getTargetCheckedState() ? mOnLayout : mOffLayout;
Fabrice Di Megliobe06e322012-09-11 17:42:45 -07001361 if (switchText != null) {
Alan Viverette661e6362014-05-12 10:55:37 -07001362 final int drawableState[] = getDrawableState();
1363 if (mTextColors != null) {
1364 mTextPaint.setColor(mTextColors.getColorForState(drawableState, 0));
1365 }
1366 mTextPaint.drawableState = drawableState;
1367
Alan Viverette4d065a02014-07-11 15:28:38 -07001368 final int cX;
1369 if (thumbDrawable != null) {
1370 final Rect bounds = thumbDrawable.getBounds();
1371 cX = bounds.left + bounds.right;
1372 } else {
Alan Viverettedec17292014-07-12 00:26:36 -07001373 cX = getWidth();
Alan Viverette4d065a02014-07-11 15:28:38 -07001374 }
1375
1376 final int left = cX / 2 - switchText.getWidth() / 2;
Alan Viverette5876ff42014-03-03 17:40:46 -08001377 final int top = (switchInnerTop + switchInnerBottom) / 2 - switchText.getHeight() / 2;
1378 canvas.translate(left, top);
Fabrice Di Megliobe06e322012-09-11 17:42:45 -07001379 switchText.draw(canvas);
1380 }
Adam Powell12190b32010-11-28 19:07:53 -08001381
Alan Viverette5876ff42014-03-03 17:40:46 -08001382 canvas.restoreToCount(saveCount);
Adam Powell12190b32010-11-28 19:07:53 -08001383 }
1384
1385 @Override
Fabrice Di Meglio28efba32012-06-01 16:52:31 -07001386 public int getCompoundPaddingLeft() {
1387 if (!isLayoutRtl()) {
1388 return super.getCompoundPaddingLeft();
1389 }
1390 int padding = super.getCompoundPaddingLeft() + mSwitchWidth;
1391 if (!TextUtils.isEmpty(getText())) {
1392 padding += mSwitchPadding;
1393 }
1394 return padding;
1395 }
1396
1397 @Override
Adam Powell12190b32010-11-28 19:07:53 -08001398 public int getCompoundPaddingRight() {
Fabrice Di Meglio28efba32012-06-01 16:52:31 -07001399 if (isLayoutRtl()) {
1400 return super.getCompoundPaddingRight();
1401 }
Adam Powell12190b32010-11-28 19:07:53 -08001402 int padding = super.getCompoundPaddingRight() + mSwitchWidth;
1403 if (!TextUtils.isEmpty(getText())) {
1404 padding += mSwitchPadding;
1405 }
1406 return padding;
1407 }
1408
Alan Viverettecc2688d2013-09-17 17:00:12 -07001409 /**
1410 * Translates thumb position to offset according to current RTL setting and
Alan Viverette0c0dde72014-07-30 13:29:39 -07001411 * thumb scroll range. Accounts for both track and thumb padding.
Alan Viverettecc2688d2013-09-17 17:00:12 -07001412 *
1413 * @return thumb offset
1414 */
1415 private int getThumbOffset() {
1416 final float thumbPosition;
1417 if (isLayoutRtl()) {
1418 thumbPosition = 1 - mThumbPosition;
1419 } else {
1420 thumbPosition = mThumbPosition;
1421 }
1422 return (int) (thumbPosition * getThumbScrollRange() + 0.5f);
1423 }
1424
Adam Powell12190b32010-11-28 19:07:53 -08001425 private int getThumbScrollRange() {
Alan Viverette4d065a02014-07-11 15:28:38 -07001426 if (mTrackDrawable != null) {
Alan Viverette0c0dde72014-07-30 13:29:39 -07001427 final Rect padding = mTempRect;
1428 mTrackDrawable.getPadding(padding);
1429
1430 final Insets insets;
1431 if (mThumbDrawable != null) {
1432 insets = mThumbDrawable.getOpticalInsets();
1433 } else {
1434 insets = Insets.NONE;
1435 }
1436
1437 return mSwitchWidth - mThumbWidth - padding.left - padding.right
1438 - insets.left - insets.right;
Alan Viverette4d065a02014-07-11 15:28:38 -07001439 } else {
Adam Powell12190b32010-11-28 19:07:53 -08001440 return 0;
1441 }
Adam Powell12190b32010-11-28 19:07:53 -08001442 }
1443
1444 @Override
1445 protected int[] onCreateDrawableState(int extraSpace) {
1446 final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
1447 if (isChecked()) {
1448 mergeDrawableStates(drawableState, CHECKED_STATE_SET);
1449 }
1450 return drawableState;
1451 }
1452
1453 @Override
1454 protected void drawableStateChanged() {
1455 super.drawableStateChanged();
1456
Alan Viverettead0020f2015-09-04 10:10:42 -04001457 final int[] state = getDrawableState();
1458 boolean changed = false;
Adam Powell12190b32010-11-28 19:07:53 -08001459
Alan Viverettead0020f2015-09-04 10:10:42 -04001460 final Drawable thumbDrawable = mThumbDrawable;
1461 if (thumbDrawable != null && thumbDrawable.isStateful()) {
1462 changed |= thumbDrawable.setState(state);
Alan Viverette661e6362014-05-12 10:55:37 -07001463 }
1464
Alan Viverettead0020f2015-09-04 10:10:42 -04001465 final Drawable trackDrawable = mTrackDrawable;
1466 if (trackDrawable != null && trackDrawable.isStateful()) {
1467 changed |= trackDrawable.setState(state);
Alan Viverette661e6362014-05-12 10:55:37 -07001468 }
Adam Powell12190b32010-11-28 19:07:53 -08001469
Alan Viverettead0020f2015-09-04 10:10:42 -04001470 if (changed) {
1471 invalidate();
1472 }
Adam Powell12190b32010-11-28 19:07:53 -08001473 }
1474
Alan Viverettecebc6ba2014-06-13 15:52:13 -07001475 @Override
Alan Viverette8de14942014-06-18 18:05:15 -07001476 public void drawableHotspotChanged(float x, float y) {
1477 super.drawableHotspotChanged(x, y);
Alan Viverettecebc6ba2014-06-13 15:52:13 -07001478
1479 if (mThumbDrawable != null) {
1480 mThumbDrawable.setHotspot(x, y);
1481 }
1482
1483 if (mTrackDrawable != null) {
1484 mTrackDrawable.setHotspot(x, y);
1485 }
1486 }
1487
Adam Powell12190b32010-11-28 19:07:53 -08001488 @Override
Alan Viverettef6d87ec2016-03-11 10:09:14 -05001489 protected boolean verifyDrawable(@NonNull Drawable who) {
Adam Powell12190b32010-11-28 19:07:53 -08001490 return super.verifyDrawable(who) || who == mThumbDrawable || who == mTrackDrawable;
1491 }
1492
1493 @Override
1494 public void jumpDrawablesToCurrentState() {
1495 super.jumpDrawablesToCurrentState();
Alan Viverette4d065a02014-07-11 15:28:38 -07001496
1497 if (mThumbDrawable != null) {
1498 mThumbDrawable.jumpToCurrentState();
1499 }
1500
1501 if (mTrackDrawable != null) {
1502 mTrackDrawable.jumpToCurrentState();
1503 }
1504
Alan Viveretteee20d772015-09-23 14:23:21 -04001505 if (mPositionAnimator != null && mPositionAnimator.isStarted()) {
Alan Viverette4d065a02014-07-11 15:28:38 -07001506 mPositionAnimator.end();
1507 mPositionAnimator = null;
1508 }
Adam Powell12190b32010-11-28 19:07:53 -08001509 }
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -08001510
1511 @Override
Dianne Hackborna7bb6fb2015-02-03 18:13:40 -08001512 public CharSequence getAccessibilityClassName() {
1513 return Switch.class.getName();
1514 }
1515
Felipe Leme92ab3852018-11-15 11:30:40 -08001516 /** @hide */
Dianne Hackborna7bb6fb2015-02-03 18:13:40 -08001517 @Override
Felipe Leme92ab3852018-11-15 11:30:40 -08001518 protected void onProvideStructure(@NonNull ViewStructure structure,
1519 @ViewStructureType int viewFor, int flags) {
Dianne Hackborna7bb6fb2015-02-03 18:13:40 -08001520 CharSequence switchText = isChecked() ? mTextOn : mTextOff;
1521 if (!TextUtils.isEmpty(switchText)) {
Dianne Hackborna83ce1d2015-03-11 15:16:13 -07001522 CharSequence oldText = structure.getText();
Dianne Hackborna7bb6fb2015-02-03 18:13:40 -08001523 if (TextUtils.isEmpty(oldText)) {
Dianne Hackborna83ce1d2015-03-11 15:16:13 -07001524 structure.setText(switchText);
Dianne Hackborna7bb6fb2015-02-03 18:13:40 -08001525 } else {
1526 StringBuilder newText = new StringBuilder();
1527 newText.append(oldText).append(' ').append(switchText);
Dianne Hackborna83ce1d2015-03-11 15:16:13 -07001528 structure.setText(newText);
Dianne Hackborna7bb6fb2015-02-03 18:13:40 -08001529 }
James Cook5cfaae42015-05-28 15:52:44 -07001530 // The style of the label text is provided via the base TextView class. This is more
1531 // relevant than the style of the (optional) on/off text on the switch button itself,
1532 // so ignore the size/color/style stored this.mTextPaint.
Dianne Hackborna7bb6fb2015-02-03 18:13:40 -08001533 }
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -08001534 }
1535
Alan Viverettecc2688d2013-09-17 17:00:12 -07001536 private static final FloatProperty<Switch> THUMB_POS = new FloatProperty<Switch>("thumbPos") {
1537 @Override
1538 public Float get(Switch object) {
1539 return object.mThumbPosition;
1540 }
1541
1542 @Override
1543 public void setValue(Switch object, float value) {
1544 object.setThumbPosition(value);
1545 }
1546 };
Adam Powell12190b32010-11-28 19:07:53 -08001547}