/
MaterialSwitch.java
693 lines (610 loc) · 23.7 KB
/
MaterialSwitch.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
/*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.material.materialswitch;
import com.google.android.material.R;
import static androidx.core.graphics.ColorUtils.blendARGB;
import static com.google.android.material.theme.overlay.MaterialThemeOverlay.wrap;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.PorterDuff;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.appcompat.graphics.drawable.AnimatedStateListDrawableCompat;
import androidx.appcompat.widget.DrawableUtils;
import androidx.appcompat.widget.SwitchCompat;
import androidx.appcompat.widget.TintTypedArray;
import android.util.AttributeSet;
import android.view.Gravity;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.graphics.drawable.DrawableCompat;
import com.google.android.material.internal.ThemeEnforcement;
import com.google.android.material.internal.ViewUtils;
import java.lang.reflect.Field;
import java.util.Arrays;
/**
* A class that creates a Material Themed Switch. This class is intended to provide a brand new
* Switch design and replace the obsolete
* {@link com.google.android.material.switchmaterial.SwitchMaterial} class.
*/
public class MaterialSwitch extends SwitchCompat {
private static final int DEF_STYLE_RES = R.style.Widget_Material3_CompoundButton_MaterialSwitch;
private static final int[] STATE_SET_WITH_ICON = { R.attr.state_with_icon };
@NonNull private final SwitchWidth switchWidth = SwitchWidth.create(this);
@NonNull private final ThumbPosition thumbPosition = new ThumbPosition();
@Nullable private Drawable thumbDrawable;
@Nullable private Drawable thumbIconDrawable;
@Nullable private Drawable trackDrawable;
@Nullable private Drawable trackDecorationDrawable;
@Nullable private ColorStateList thumbTintList;
@Nullable private ColorStateList thumbIconTintList;
@NonNull private PorterDuff.Mode thumbIconTintMode;
@Nullable private ColorStateList trackTintList;
@Nullable private ColorStateList trackDecorationTintList;
@NonNull private PorterDuff.Mode trackDecorationTintMode;
public MaterialSwitch(@NonNull Context context) {
this(context, null);
}
public MaterialSwitch(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, R.attr.materialSwitchStyle);
}
public MaterialSwitch(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(wrap(context, attrs, defStyleAttr, DEF_STYLE_RES), attrs, defStyleAttr);
// Ensure we are using the correctly themed context rather than the context that was passed in.
context = getContext();
thumbDrawable = super.getThumbDrawable();
thumbTintList = super.getThumbTintList();
super.setThumbTintList(null); // Always use our custom tinting logic
trackDrawable = super.getTrackDrawable();
trackTintList = super.getTrackTintList();
super.setTrackTintList(null); // Always use our custom tinting logic
TintTypedArray attributes =
ThemeEnforcement.obtainTintedStyledAttributes(
context, attrs, R.styleable.MaterialSwitch, defStyleAttr, DEF_STYLE_RES);
thumbIconDrawable = attributes.getDrawable(R.styleable.MaterialSwitch_thumbIcon);
thumbIconTintList = attributes.getColorStateList(R.styleable.MaterialSwitch_thumbIconTint);
thumbIconTintMode =
DrawableUtils.parseTintMode(
attributes.getInt(R.styleable.MaterialSwitch_thumbIconTintMode, -1), Mode.SRC_IN);
trackDecorationDrawable =
attributes.getDrawable(R.styleable.MaterialSwitch_trackDecoration);
trackDecorationTintList =
attributes.getColorStateList(R.styleable.MaterialSwitch_trackDecorationTint);
trackDecorationTintMode =
DrawableUtils.parseTintMode(
attributes.getInt(R.styleable.MaterialSwitch_trackDecorationTintMode, -1), Mode.SRC_IN);
attributes.recycle();
refreshThumbDrawable();
refreshTrackDrawable();
}
// TODO(b/227338106): remove this workaround and move to use setEnforceSwitchWidth(false) after
// AppCompat 1.6.0-stable is released.
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
switchWidth.set(getSwitchMinWidth());
}
@Override
public void invalidate() {
// ThumbPosition update will trigger invalidate(), update thumb/track tint here.
if (thumbPosition != null) {
// This may happen when super classes' constructors call this method.
updateDrawableTints();
}
super.invalidate();
}
@Override
protected int[] onCreateDrawableState(int extraSpace) {
int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
if (thumbIconDrawable != null) {
mergeDrawableStates(drawableState, STATE_SET_WITH_ICON);
}
return drawableState;
}
// TODO(b/227338106): remove this workaround and move to use setEnforceSwitchWidth(false) after
// AppCompat 1.6.0-stable is released.
@Override
public int getCompoundPaddingLeft() {
if (!ViewUtils.isLayoutRtl(this)) {
return super.getCompoundPaddingLeft();
}
// Compound paddings are used during onMeasure() to decide the component width, at that time
// the switch width is not overridden yet so we need to adjust the value to make measurement
// right. This can be removed after the workaround is removed.
return super.getCompoundPaddingLeft() - switchWidth.get() + getSwitchMinWidth();
}
// TODO(b/227338106): remove this workaround and move to use setEnforceSwitchWidth(false) after
// AppCompat 1.6.0-stable is released.
@Override
public int getCompoundPaddingRight() {
if (ViewUtils.isLayoutRtl(this)) {
return super.getCompoundPaddingRight();
}
// Compound paddings are used during onMeasure() to decide the component width, at that time
// the switch width is not overridden yet so we need to adjust the value to make measurement
// right. This can be removed after the workaround is removed.
return super.getCompoundPaddingRight() - switchWidth.get() + getSwitchMinWidth();
}
@Override
public void setThumbDrawable(@Nullable Drawable drawable) {
thumbDrawable = drawable;
refreshThumbDrawable();
}
@Override
@Nullable
public Drawable getThumbDrawable() {
return thumbDrawable;
}
@Override
public void setThumbTintList(@Nullable ColorStateList tintList) {
thumbTintList = tintList;
refreshThumbDrawable();
}
@Override
@Nullable
public ColorStateList getThumbTintList() {
return thumbTintList;
}
@Override
public void setThumbTintMode(@Nullable PorterDuff.Mode tintMode) {
super.setThumbTintMode(tintMode);
refreshThumbDrawable();
}
/**
* Sets the drawable used for the thumb icon that will be drawn upon the thumb.
*
* @param resId Resource ID of a thumb icon drawable
*
* @attr ref com.google.android.material.R.styleable#MaterialSwitch_thumbIcon
*/
public void setThumbIconResource(@DrawableRes int resId) {
setThumbIconDrawable(AppCompatResources.getDrawable(getContext(), resId));
}
/**
* Sets the drawable used for the thumb icon that will be drawn upon the thumb.
*
* @param icon Thumb icon drawable
*
* @attr ref com.google.android.material.R.styleable#MaterialSwitch_thumbIcon
*/
public void setThumbIconDrawable(@Nullable Drawable icon) {
thumbIconDrawable = icon;
refreshThumbDrawable();
}
/**
* Gets the drawable used for the thumb icon that will be drawn upon the thumb.
*
* @attr ref com.google.android.material.R.styleable#MaterialSwitch_thumbIcon
*/
@Nullable
public Drawable getThumbIconDrawable() {
return thumbIconDrawable;
}
/**
* Applies a tint to the thumb icon drawable. Does not modify the current
* tint mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
* <p>
* Subsequent calls to {@link #setThumbIconDrawable(Drawable)} will
* automatically mutate the drawable and apply the specified tint and tint
* mode using {@link DrawableCompat#setTintList(Drawable, ColorStateList)}.
*
* @param tintList the tint to apply, may be {@code null} to clear tint
*
* @attr ref com.google.android.material.R.styleable#MaterialSwitch_thumbIconTint
*/
public void setThumbIconTintList(@Nullable ColorStateList tintList) {
thumbIconTintList = tintList;
refreshThumbDrawable();
}
/**
* Returns the tint applied to the thumb icon drawable
*
* @attr ref com.google.android.material.R.styleable#MaterialSwitch_thumbIconTint
*/
@Nullable
public ColorStateList getThumbIconTintList() {
return thumbIconTintList;
}
/**
* Specifies the blending mode used to apply the tint specified by
* {@link #setThumbIconTintList(ColorStateList)}} to the thumb icon drawable.
* The default mode is {@link PorterDuff.Mode#SRC_IN}.
*
* @param tintMode the blending mode used to apply the tint
* @attr ref com.google.android.material.R.styleable#MaterialSwitch_thumbIconTintMode
*/
public void setThumbIconTintMode(@NonNull PorterDuff.Mode tintMode) {
thumbIconTintMode = tintMode;
refreshThumbDrawable();
}
/**
* Returns the blending mode used to apply the tint to the thumb icon drawable
*
* @attr ref com.google.android.material.R.styleable#MaterialSwitch_thumbIconTintMode
*/
@NonNull
public PorterDuff.Mode getThumbIconTintMode() {
return thumbIconTintMode;
}
@Override
public void setTrackDrawable(@Nullable Drawable track) {
trackDrawable = track;
refreshTrackDrawable();
}
@Override
@Nullable
public Drawable getTrackDrawable() {
return trackDrawable;
}
@Override
public void setTrackTintList(@Nullable ColorStateList tintList) {
trackTintList = tintList;
refreshTrackDrawable();
}
@Override
@Nullable
public ColorStateList getTrackTintList() {
return trackTintList;
}
@Override
public void setTrackTintMode(@Nullable PorterDuff.Mode tintMode) {
super.setTrackTintMode(tintMode);
refreshTrackDrawable();
}
/**
* Set the drawable used for the track decoration that will be drawn upon the track.
*
* @param resId Resource ID of a track decoration drawable
*
* @attr ref com.google.android.material.R.styleable#MaterialSwitch_trackDecoration
*/
public void setTrackDecorationResource(@DrawableRes int resId) {
setTrackDecorationDrawable(AppCompatResources.getDrawable(getContext(), resId));
}
/**
* Set the drawable used for the track decoration that will be drawn upon the track.
*
* @param trackDecoration Track decoration drawable
*
* @attr ref com.google.android.material.R.styleable#MaterialSwitch_trackDecoration
*/
public void setTrackDecorationDrawable(@Nullable Drawable trackDecoration) {
trackDecorationDrawable = trackDecoration;
refreshTrackDrawable();
}
/**
* Get the drawable used for the track decoration that will be drawn upon the track.
*
* @attr ref com.google.android.material.R.styleable#MaterialSwitch_trackDecoration
*/
@Nullable
public Drawable getTrackDecorationDrawable() {
return trackDecorationDrawable;
}
/**
* Applies a tint to the track decoration drawable. Does not modify the current
* tint mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
*
* <p>Subsequent calls to {@link #setTrackDecorationDrawable(Drawable)} will
* automatically mutate the drawable and apply the specified tint and tint
* mode using {@link DrawableCompat#setTintList(Drawable, ColorStateList)}.
*
* @param tintList the tint to apply, may be {@code null} to clear tint
*
* @attr ref com.google.android.material.R.styleable#MaterialSwitch_trackDecorationTint
*/
public void setTrackDecorationTintList(@Nullable ColorStateList tintList) {
trackDecorationTintList = tintList;
refreshTrackDrawable();
}
/**
* Returns the tint applied to the track decoration drawable
*
* @attr ref com.google.android.material.R.styleable#MaterialSwitch_trackDecorationTint
*/
@Nullable
public ColorStateList getTrackDecorationTintList() {
return trackDecorationTintList;
}
/**
* Specifies the blending mode used to apply the tint specified by
* {@link #setTrackDecorationTintList(ColorStateList)}} to the track decoration drawable.
* The default mode is {@link PorterDuff.Mode#SRC_IN}.
*
* @param tintMode the blending mode used to apply the tint
* @attr ref com.google.android.material.R.styleable#MaterialSwitch_trackDecorationTintMode
*/
public void setTrackDecorationTintMode(@NonNull PorterDuff.Mode tintMode) {
trackDecorationTintMode = tintMode;
refreshTrackDrawable();
}
/**
* Returns the blending mode used to apply the tint to the track decoration drawable
*
* @attr ref com.google.android.material.R.styleable#MaterialSwitch_trackDecorationTintMode
*/
@NonNull
public PorterDuff.Mode getTrackDecorationTintMode() {
return trackDecorationTintMode;
}
// TODO(b/227338106): remove this workaround to use super.getThumbPosition() directly after
// AppCompat 1.6.0-stable is released.
private float getThumbPos() {
return thumbPosition.get();
}
private void refreshThumbDrawable() {
thumbDrawable =
createTintableDrawableIfNeeded(thumbDrawable, thumbTintList, getThumbTintMode());
thumbIconDrawable =
createTintableDrawableIfNeeded(thumbIconDrawable, thumbIconTintList, thumbIconTintMode);
updateDrawableTints();
super.setThumbDrawable(compositeThumbAndIconDrawable(thumbDrawable, thumbIconDrawable));
refreshDrawableState();
}
@Nullable
private static Drawable compositeThumbAndIconDrawable(
@Nullable Drawable thumbDrawable, @Nullable Drawable thumbIconDrawable) {
if (thumbDrawable == null) {
return thumbIconDrawable;
}
if (thumbIconDrawable == null) {
return thumbDrawable;
}
LayerDrawable drawable = new LayerDrawable(new Drawable[]{thumbDrawable, thumbIconDrawable});
int iconNewWidth;
int iconNewHeight;
if (thumbIconDrawable.getIntrinsicWidth() <= thumbDrawable.getIntrinsicWidth()
&& thumbIconDrawable.getIntrinsicHeight() <= thumbDrawable.getIntrinsicHeight()) {
// If the icon is smaller than the thumb in both its width and height, keep icon's size.
iconNewWidth = thumbIconDrawable.getIntrinsicWidth();
iconNewHeight = thumbIconDrawable.getIntrinsicHeight();
} else {
float thumbIconRatio =
(float) thumbIconDrawable.getIntrinsicWidth() / thumbIconDrawable.getIntrinsicHeight();
float thumbRatio =
(float) thumbDrawable.getIntrinsicWidth() / thumbDrawable.getIntrinsicHeight();
if (thumbIconRatio >= thumbRatio) {
// If the icon is wider in ratio than the thumb, shrink it according to its width.
iconNewWidth = thumbDrawable.getIntrinsicWidth();
iconNewHeight = (int) (iconNewWidth / thumbIconRatio);
} else {
// If the icon is taller in ratio than the thumb, shrink it according to its height.
iconNewHeight = thumbDrawable.getIntrinsicHeight();
iconNewWidth = (int) (thumbIconRatio * iconNewHeight);
}
}
// Centers the icon inside the thumb. Before M there's no layer gravity support, we need to use
// layer insets to adjust the icon position manually.
if (VERSION.SDK_INT >= VERSION_CODES.M) {
drawable.setLayerSize(1, iconNewWidth, iconNewHeight);
drawable.setLayerGravity(1, Gravity.CENTER);
} else {
int horizontalInset = (thumbDrawable.getIntrinsicWidth() - iconNewWidth) / 2;
int verticalInset = (thumbDrawable.getIntrinsicHeight() - iconNewHeight) / 2;
drawable.setLayerInset(1, horizontalInset, verticalInset, horizontalInset, verticalInset);
}
return drawable;
}
private void refreshTrackDrawable() {
trackDrawable =
createTintableDrawableIfNeeded(trackDrawable, trackTintList, getTrackTintMode());
trackDecorationDrawable =
createTintableDrawableIfNeeded(
trackDecorationDrawable, trackDecorationTintList, trackDecorationTintMode);
updateDrawableTints();
Drawable finalTrackDrawable;
if (trackDrawable != null && trackDecorationDrawable != null) {
finalTrackDrawable =
new LayerDrawable(new Drawable[]{ trackDrawable, trackDecorationDrawable});
} else if (trackDrawable != null) {
finalTrackDrawable = trackDrawable;
} else {
finalTrackDrawable = trackDecorationDrawable;
}
if (finalTrackDrawable != null) {
setSwitchMinWidth(finalTrackDrawable.getIntrinsicWidth());
}
super.setTrackDrawable(finalTrackDrawable);
}
private void updateDrawableTints() {
if (thumbTintList == null
&& thumbIconTintList == null
&& trackTintList == null
&& trackDecorationTintList == null) {
// Early return to avoid heavy operation.
return;
}
float thumbPosition = getThumbPos();
int[] currentState = getDrawableState();
int[] currentStateUnchecked = getUncheckedState(currentState);
int[] currentStateChecked = getCheckedState(currentState);
if (thumbTintList != null) {
setInterpolatedDrawableTintIfPossible(
thumbDrawable, thumbTintList, currentStateUnchecked, currentStateChecked, thumbPosition);
}
if (thumbIconTintList != null) {
setInterpolatedDrawableTintIfPossible(
thumbIconDrawable,
thumbIconTintList,
currentStateUnchecked,
currentStateChecked,
thumbPosition);
}
if (trackTintList != null) {
setInterpolatedDrawableTintIfPossible(
trackDrawable, trackTintList, currentStateUnchecked, currentStateChecked, thumbPosition);
}
if (trackDecorationTintList != null) {
setInterpolatedDrawableTintIfPossible(
trackDecorationDrawable,
trackDecorationTintList,
currentStateUnchecked,
currentStateChecked,
thumbPosition);
}
}
/** Returns a new state that removes the checked state from the input state. */
private static int[] getUncheckedState(int[] state) {
int[] newState = new int[state.length];
int i = 0;
for (int subState : state) {
if (subState != android.R.attr.state_checked) {
newState[i++] = subState;
}
}
return newState;
}
/** Returns a new state that adds the checked state to the input state. */
private static int[] getCheckedState(int[] state) {
for (int i = 0; i < state.length; i++) {
if (state[i] == android.R.attr.state_checked) {
return state;
} else if (state[i] == 0) {
int[] newState = state.clone();
newState[i] = android.R.attr.state_checked;
return newState;
}
}
int[] newState = Arrays.copyOf(state, state.length + 1);
newState[state.length] = android.R.attr.state_checked;
return newState;
}
/**
* Tints the given drawable with the interpolated color according to the provided thumb position
* between unchecked and checked states. The reference color in unchecked and checked states will
* be retrieved from the given {@link ColorStateList} according to the provided states.
*/
private static void setInterpolatedDrawableTintIfPossible(
@Nullable Drawable drawable,
@Nullable ColorStateList tint,
@NonNull int[] stateUnchecked,
@NonNull int[] stateChecked,
float thumbPosition) {
if (drawable == null || tint == null) {
return;
}
// TODO(b/232529333): remove this workaround after updating AppCompat version to 1.6.
if (drawable instanceof AnimatedStateListDrawableCompat
&& VERSION.SDK_INT < VERSION_CODES.LOLLIPOP) {
DrawableCompat.setTintList(
drawable,
ColorStateList.valueOf(
blendARGB(
tint.getColorForState(stateUnchecked, 0),
tint.getColorForState(stateChecked, 0),
thumbPosition)));
return;
}
DrawableCompat.setTint(
drawable,
blendARGB(
tint.getColorForState(stateUnchecked, 0),
tint.getColorForState(stateChecked, 0),
thumbPosition));
}
private static Drawable createTintableDrawableIfNeeded(
Drawable drawable, ColorStateList tintList, Mode tintMode) {
if (drawable == null) {
return null;
}
if (tintList != null) {
drawable = DrawableCompat.wrap(drawable).mutate();
if (tintMode != null) {
DrawableCompat.setTintMode(drawable, tintMode);
}
}
return drawable;
}
// TODO(b/227338106): remove this workaround and move to use setEnforceSwitchWidth(false) after
// AppCompat 1.6.0-stable is released.
@SuppressLint("PrivateApi")
private static final class SwitchWidth {
@NonNull private final MaterialSwitch materialSwitch;
@Nullable private final Field switchWidthField;
@NonNull
static SwitchWidth create(@NonNull MaterialSwitch materialSwitch) {
return new SwitchWidth(materialSwitch, createSwitchWidthField());
}
private SwitchWidth(@NonNull MaterialSwitch materialSwitch, @Nullable Field switchWidthField) {
this.materialSwitch = materialSwitch;
this.switchWidthField = switchWidthField;
}
int get() {
try {
if (switchWidthField != null) {
return switchWidthField.getInt(materialSwitch);
}
} catch (IllegalAccessException e) {
// Fall through
}
// Return getSwitchMinWidth() so no width adjustment will be done.
return materialSwitch.getSwitchMinWidth();
}
void set(int switchWidth) {
try {
if (switchWidthField != null) {
switchWidthField.setInt(materialSwitch, switchWidth);
}
} catch (IllegalAccessException e) {
// Fall through
}
}
@Nullable
private static Field createSwitchWidthField() {
try {
Field switchWidthField = SwitchCompat.class.getDeclaredField("mSwitchWidth");
switchWidthField.setAccessible(true);
return switchWidthField;
} catch (NoSuchFieldException | SecurityException e) {
return null;
}
}
}
// TODO(b/227338106): remove this workaround to use super.getThumbPosition() directly after
// AppCompat 1.6.0-stable is released.
@SuppressLint("PrivateApi")
private final class ThumbPosition {
private final Field thumbPositionField;
private ThumbPosition() {
thumbPositionField = createThumbPositionField();
}
float get() {
try {
if (thumbPositionField != null) {
return thumbPositionField.getFloat(MaterialSwitch.this);
}
} catch (IllegalAccessException e) {
// Fall through
}
return isChecked() ? 1 : 0;
}
private Field createThumbPositionField() {
try {
Field thumbPositionField = SwitchCompat.class.getDeclaredField("mThumbPosition");
thumbPositionField.setAccessible(true);
return thumbPositionField;
} catch (Exception e) {
return null;
}
}
}
}