/
ChipDrawable.java
2470 lines (2157 loc) · 80.6 KB
/
ChipDrawable.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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2017 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
*
* https://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.chip;
import com.google.android.material.R;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Outline;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.FontMetrics;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.PointF;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.Drawable.Callback;
import android.graphics.drawable.RippleDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.os.Build.VERSION_CODES;
import androidx.appcompat.content.res.AppCompatResources;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.AnimatorRes;
import androidx.annotation.AttrRes;
import androidx.annotation.BoolRes;
import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.annotation.DimenRes;
import androidx.annotation.Dimension;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.Px;
import androidx.annotation.StringRes;
import androidx.annotation.StyleRes;
import androidx.annotation.XmlRes;
import androidx.core.graphics.ColorUtils;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.core.graphics.drawable.TintAwareDrawable;
import androidx.core.text.BidiFormatter;
import androidx.core.view.ViewCompat;
import com.google.android.material.animation.MotionSpec;
import com.google.android.material.canvas.CanvasCompat;
import com.google.android.material.color.MaterialColors;
import com.google.android.material.drawable.DrawableUtils;
import com.google.android.material.internal.TextDrawableHelper;
import com.google.android.material.internal.TextDrawableHelper.TextDrawableDelegate;
import com.google.android.material.internal.ThemeEnforcement;
import com.google.android.material.internal.ViewUtils;
import com.google.android.material.resources.MaterialResources;
import com.google.android.material.resources.TextAppearance;
import com.google.android.material.ripple.RippleUtils;
import com.google.android.material.shape.MaterialShapeDrawable;
import com.google.android.material.shape.ShapeAppearanceModel;
import java.lang.ref.WeakReference;
import java.util.Arrays;
/**
* ChipDrawable contains all the layout and draw logic for {@link Chip}.
*
* <p>You can use ChipDrawable directly in contexts that require a Drawable. For example, an
* auto-complete enabled EditText can replace snippets of text with a ChipDrawable to represent it
* as a semantic entity. To create an instance of ChipDrawable, use {@link
* ChipDrawable#createFromResource(Context, int)} and pass in an XML resource in this form:
*
* <pre>{@code
* <chip xmlns:app="http://schemas.android.com/apk/res-auto"
* android:text="Hello, World!"/>
* }</pre>
*
* <p>The basic attributes you can set are:
*
* <ul>
* <li>{@link android.R.attr#checkable android:checkable} - If true, the chip can be toggled. If
* false, the chip acts like a button.
* <li>{@link android.R.attr#text android:text} - Sets the text of the chip.
* <li>{@code app:chipIcon} - Sets the icon of the chip, or use @null to display no icon. Usually
* on the left.
* <li>{@code app:checkedIcon} - Sets a custom icon to use when checked, or use @null to display
* no icon. Usually on the left.
* <li>{@code app:closeIcon} - Sets a custom icon that the user can click to close, or use @null
* to display no icon. Usually on the right.
* <li>{@link android.R.attr#ellipsize} - Does not support {@link
* android.text.TextUtils.TruncateAt#MARQUEE} because chip text should not scroll.
* </ul>
*
* <p>When used in this stand-alone mode, the host view must explicitly manage the ChipDrawable's
* state:
*
* <ul>
* <li>{@link ChipDrawable#setBounds(int, int, int, int)}, taking into account {@link
* ChipDrawable#getIntrinsicHeight()} and {@link ChipDrawable#getIntrinsicWidth()}.
* <li>{@link ChipDrawable#draw(Canvas)}
* <li>{@link ChipDrawable#setCallback(Callback)}, to support invalidations on the chip drawable
* or any of its child drawables. This includes animations.
* <li>{@link ChipDrawable#setState(int[])}, to support checking the chip, and
* touch/mouse/keyboard interactions on the chip.
* <li>{@link ChipDrawable#setCloseIconState(int[])}, to support touch, mouse, or keyboard
* interactions on the close icon.
* <li>{@link ChipDrawable#setHotspot(float, float)}
* <li>{@link ChipDrawable#setLayoutDirection(int)}, to support RTL mode.
* </ul>
*
* <p>ChipDrawable's horizontal layout is as follows:
*
* <pre>
* chipStartPadding iconEndPadding closeIconStartPadding chipEndPadding
* + + + +
* | | | |
* | iconStartPadding | textStartPadding textEndPadding | closeIconEndPadding |
* | + | + + | + |
* | | | | | | | |
* v v v v v v v v
* +-----+----+-----------+----+----+---------------------+----+----+----------+----+-----+
* | | | XX | | | XX X X X XXX | | | X X | | |
* | | | XX | | | X X X X X X X | | | XX XX | | |
* | | | XX XX | | | X XXXX X XXX | | | XX | | |
* | | | XXX | | | X X X X X X | | | XX XX | | |
* | | | X | | | XX X X X X | | | X X | | |
* +-----+----+-----------+----+----+---------------------+----+----+----------+----+-----+
* ^ ^ ^
* | | |
* + + +
* chipIconSize *dynamic* closeIconSize
* </pre>
*
* <p>ChipDrawable contains three child drawables: {@code chipIcon}, {@code checkedIcon}, and {@code
* closeIcon}. chipIcon and checkedIcon inherit the state of this drawable, but closeIcon contains
* its own state that you can set with {@link #setCloseIconState(int[])}.
*
* @see Chip
*/
public class ChipDrawable extends MaterialShapeDrawable
implements TintAwareDrawable, Callback, TextDrawableDelegate {
private static final boolean DEBUG = false;
private static final int[] DEFAULT_STATE = new int[] {android.R.attr.state_enabled};
private static final String NAMESPACE_APP = "http://schemas.android.com/apk/res-auto";
private static final int MAX_CHIP_ICON_HEIGHT = 24; // dp
private static final ShapeDrawable closeIconRippleMask = new ShapeDrawable(new OvalShape());
// Visuals
@Nullable private ColorStateList chipSurfaceColor;
@Nullable private ColorStateList chipBackgroundColor;
private float chipMinHeight;
private float chipCornerRadius = -1;
@Nullable private ColorStateList chipStrokeColor;
private float chipStrokeWidth;
@Nullable private ColorStateList rippleColor;
// Text
@Nullable private CharSequence text;
// Chip icon
private boolean chipIconVisible;
@Nullable private Drawable chipIcon;
@Nullable private ColorStateList chipIconTint;
private float chipIconSize;
private boolean hasChipIconTint;
// Close icon
private boolean closeIconVisible;
@Nullable private Drawable closeIcon;
@Nullable private Drawable closeIconRipple;
@Nullable private ColorStateList closeIconTint;
private float closeIconSize;
@Nullable private CharSequence closeIconContentDescription;
// Checkable
private boolean checkable;
private boolean checkedIconVisible;
@Nullable private Drawable checkedIcon;
@Nullable private ColorStateList checkedIconTint;
// Animations
@Nullable private MotionSpec showMotionSpec;
@Nullable private MotionSpec hideMotionSpec;
// The following attributes are adjustable padding on the chip, listed from start to end.
// Chip starts here.
/** Padding at the start of the chip, before the icon. */
private float chipStartPadding;
/** Padding at the start of the icon, after the start of the chip. If icon exists. */
private float iconStartPadding;
// Icon is here.
/** Padding at the end of the icon, before the text. If icon exists. */
private float iconEndPadding;
/** Padding at the start of the text, after the icon. */
private float textStartPadding;
// Text is here.
/** Padding at the end of the text, before the close icon. */
private float textEndPadding;
/** Padding at the start of the close icon, after the text. If close icon exists. */
private float closeIconStartPadding;
// Close icon is here.
/** Padding at the end of the close icon, before the end of the chip. If close icon exists. */
private float closeIconEndPadding;
/** Padding at the end of the chip, after the close icon. */
private float chipEndPadding;
// Chip ends here.
@NonNull private final Context context;
private final Paint chipPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
@Nullable private final Paint debugPaint;
private final FontMetrics fontMetrics = new FontMetrics();
private final RectF rectF = new RectF();
private final PointF pointF = new PointF();
private final Path shapePath = new Path();
@NonNull private final TextDrawableHelper textDrawableHelper;
@ColorInt private int currentChipSurfaceColor;
@ColorInt private int currentChipBackgroundColor;
@ColorInt private int currentCompositeSurfaceBackgroundColor;
@ColorInt private int currentChipStrokeColor;
@ColorInt private int currentCompatRippleColor;
@ColorInt private int currentTextColor;
private boolean currentChecked;
@ColorInt private int currentTint;
private int alpha = 255;
@Nullable private ColorFilter colorFilter;
@Nullable private PorterDuffColorFilter tintFilter;
@Nullable private ColorStateList tint;
@Nullable private Mode tintMode = Mode.SRC_IN;
private int[] closeIconStateSet;
private boolean useCompatRipple;
@Nullable private ColorStateList compatRippleColor;
@NonNull private WeakReference<Delegate> delegate = new WeakReference<>(null);
private TruncateAt truncateAt;
private boolean shouldDrawText;
private int maxWidth;
private boolean isShapeThemingEnabled;
/** Returns a ChipDrawable from the given attributes. */
@NonNull
public static ChipDrawable createFromAttributes(
@NonNull Context context,
@Nullable AttributeSet attrs,
@AttrRes int defStyleAttr,
@StyleRes int defStyleRes) {
ChipDrawable chip = new ChipDrawable(context, attrs, defStyleAttr, defStyleRes);
chip.loadFromAttributes(attrs, defStyleAttr, defStyleRes);
return chip;
}
/**
* Returns a ChipDrawable from the given XML resource. All attributes from {@link
* R.styleable#Chip} and a custom <code>style</code> attribute are supported. A chip resource may
* look like:
*
* <pre>{@code
* <chip
* xmlns:app="http://schemas.android.com/apk/res-auto"
* style="@style/Widget.MaterialComponents.Chip.Entry"
* app:chipIcon="@drawable/custom_icon"/>
* }</pre>
*/
@NonNull
public static ChipDrawable createFromResource(@NonNull Context context, @XmlRes int id) {
AttributeSet attrs = DrawableUtils.parseDrawableXml(context, id, "chip");
@StyleRes int style = attrs.getStyleAttribute();
if (style == 0) {
style = R.style.Widget_MaterialComponents_Chip_Entry;
}
return createFromAttributes(context, attrs, R.attr.chipStandaloneStyle, style);
}
private ChipDrawable(
@NonNull Context context,
AttributeSet attrs,
@AttrRes int defStyleAttr,
@StyleRes int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initializeElevationOverlay(context);
this.context = context;
textDrawableHelper = new TextDrawableHelper(/* delegate= */ this);
text = "";
textDrawableHelper.getTextPaint().density = context.getResources().getDisplayMetrics().density;
debugPaint = DEBUG ? new Paint(Paint.ANTI_ALIAS_FLAG) : null;
if (debugPaint != null) {
debugPaint.setStyle(Style.STROKE);
}
setState(DEFAULT_STATE);
setCloseIconState(DEFAULT_STATE);
shouldDrawText = true;
if (RippleUtils.USE_FRAMEWORK_RIPPLE) {
//noinspection NewApi
closeIconRippleMask.setTint(Color.WHITE);
}
}
private void loadFromAttributes(
@Nullable AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) {
TypedArray a =
ThemeEnforcement.obtainStyledAttributes(
context, attrs, R.styleable.Chip, defStyleAttr, defStyleRes);
isShapeThemingEnabled = a.hasValue(R.styleable.Chip_shapeAppearance);
setChipSurfaceColor(
MaterialResources.getColorStateList(context, a, R.styleable.Chip_chipSurfaceColor));
setChipBackgroundColor(
MaterialResources.getColorStateList(context, a, R.styleable.Chip_chipBackgroundColor));
setChipMinHeight(a.getDimension(R.styleable.Chip_chipMinHeight, 0f));
if (a.hasValue(R.styleable.Chip_chipCornerRadius)) {
setChipCornerRadius(a.getDimension(R.styleable.Chip_chipCornerRadius, 0f));
}
setChipStrokeColor(
MaterialResources.getColorStateList(context, a, R.styleable.Chip_chipStrokeColor));
setChipStrokeWidth(a.getDimension(R.styleable.Chip_chipStrokeWidth, 0f));
setRippleColor(MaterialResources.getColorStateList(context, a, R.styleable.Chip_rippleColor));
setText(a.getText(R.styleable.Chip_android_text));
TextAppearance textAppearance =
MaterialResources.getTextAppearance(context, a, R.styleable.Chip_android_textAppearance);
float textSize = a.getDimension(
R.styleable.Chip_android_textSize, textAppearance.getTextSize());
textAppearance.setTextSize(textSize);
setTextAppearance(textAppearance);
int ellipsize = a.getInt(R.styleable.Chip_android_ellipsize, 0);
// Convert to supported TextUtils.TruncateAt values
switch (ellipsize) {
case 1:
setEllipsize(TextUtils.TruncateAt.START);
break;
case 2:
setEllipsize(TextUtils.TruncateAt.MIDDLE);
break;
case 3:
setEllipsize(TextUtils.TruncateAt.END);
break;
case 4: // fall through
// Does not support TextUtils.TruncateAt.MARQUEE, chip text should not scroll.
default: // fall out
break;
}
setChipIconVisible(a.getBoolean(R.styleable.Chip_chipIconVisible, false));
// If the user explicitly sets the deprecated attribute (chipIconEnabled) but NOT the
// replacement attribute (chipIconVisible), use the value specified in the deprecated attribute.
if (attrs != null
&& attrs.getAttributeValue(NAMESPACE_APP, "chipIconEnabled") != null
&& attrs.getAttributeValue(NAMESPACE_APP, "chipIconVisible") == null) {
setChipIconVisible(a.getBoolean(R.styleable.Chip_chipIconEnabled, false));
}
setChipIcon(MaterialResources.getDrawable(context, a, R.styleable.Chip_chipIcon));
if (a.hasValue(R.styleable.Chip_chipIconTint)) {
setChipIconTint(
MaterialResources.getColorStateList(context, a, R.styleable.Chip_chipIconTint));
}
setChipIconSize(a.getDimension(R.styleable.Chip_chipIconSize, -1f));
setCloseIconVisible(a.getBoolean(R.styleable.Chip_closeIconVisible, false));
// If the user explicitly sets the deprecated attribute (closeIconEnabled) but NOT the
// replacement attribute (closeIconVisible), use the value specified in the deprecated
// attribute.
if (attrs != null
&& attrs.getAttributeValue(NAMESPACE_APP, "closeIconEnabled") != null
&& attrs.getAttributeValue(NAMESPACE_APP, "closeIconVisible") == null) {
setCloseIconVisible(a.getBoolean(R.styleable.Chip_closeIconEnabled, false));
}
setCloseIcon(MaterialResources.getDrawable(context, a, R.styleable.Chip_closeIcon));
setCloseIconTint(
MaterialResources.getColorStateList(context, a, R.styleable.Chip_closeIconTint));
setCloseIconSize(a.getDimension(R.styleable.Chip_closeIconSize, 0f));
setCheckable(a.getBoolean(R.styleable.Chip_android_checkable, false));
setCheckedIconVisible(a.getBoolean(R.styleable.Chip_checkedIconVisible, false));
// If the user explicitly sets the deprecated attribute (checkedIconEnabled) but NOT the
// replacement attribute (checkedIconVisible), use the value specified in the deprecated
// attribute.
if (attrs != null
&& attrs.getAttributeValue(NAMESPACE_APP, "checkedIconEnabled") != null
&& attrs.getAttributeValue(NAMESPACE_APP, "checkedIconVisible") == null) {
setCheckedIconVisible(a.getBoolean(R.styleable.Chip_checkedIconEnabled, false));
}
setCheckedIcon(MaterialResources.getDrawable(context, a, R.styleable.Chip_checkedIcon));
if (a.hasValue(R.styleable.Chip_checkedIconTint)) {
setCheckedIconTint(
MaterialResources.getColorStateList(context, a, R.styleable.Chip_checkedIconTint));
}
setShowMotionSpec(MotionSpec.createFromAttribute(context, a, R.styleable.Chip_showMotionSpec));
setHideMotionSpec(MotionSpec.createFromAttribute(context, a, R.styleable.Chip_hideMotionSpec));
setChipStartPadding(a.getDimension(R.styleable.Chip_chipStartPadding, 0f));
setIconStartPadding(a.getDimension(R.styleable.Chip_iconStartPadding, 0f));
setIconEndPadding(a.getDimension(R.styleable.Chip_iconEndPadding, 0f));
setTextStartPadding(a.getDimension(R.styleable.Chip_textStartPadding, 0f));
setTextEndPadding(a.getDimension(R.styleable.Chip_textEndPadding, 0f));
setCloseIconStartPadding(a.getDimension(R.styleable.Chip_closeIconStartPadding, 0f));
setCloseIconEndPadding(a.getDimension(R.styleable.Chip_closeIconEndPadding, 0f));
setChipEndPadding(a.getDimension(R.styleable.Chip_chipEndPadding, 0f));
setMaxWidth(a.getDimensionPixelSize(R.styleable.Chip_android_maxWidth, Integer.MAX_VALUE));
a.recycle();
}
/** Sets whether this ChipDrawable should draw its own compatibility ripples. */
public void setUseCompatRipple(boolean useCompatRipple) {
if (this.useCompatRipple != useCompatRipple) {
this.useCompatRipple = useCompatRipple;
updateCompatRippleColor();
onStateChange(getState());
}
}
/** Returns whether this ChipDrawable should draw its own compatibility ripples. */
public boolean getUseCompatRipple() {
return useCompatRipple;
}
/** Sets the View delegate that owns this ChipDrawable. */
public void setDelegate(@Nullable Delegate delegate) {
this.delegate = new WeakReference<>(delegate);
}
/** Attempts to call {@link Delegate#onChipDrawableSizeChange()} on the delegate. */
protected void onSizeChange() {
Delegate delegate = this.delegate.get();
if (delegate != null) {
delegate.onChipDrawableSizeChange();
}
}
/**
* Returns the chip's ChipDrawable-absolute bounds (top-left is <code>
* [ChipDrawable.getBounds().left, ChipDrawable.getBounds().top]</code>).
*/
public void getChipTouchBounds(@NonNull RectF bounds) {
calculateChipTouchBounds(getBounds(), bounds);
}
/**
* Returns the close icon's ChipDrawable-absolute bounds (top-left is <code>
* [ChipDrawable.getBounds().left, ChipDrawable.getBounds().top]</code>).
*/
public void getCloseIconTouchBounds(@NonNull RectF bounds) {
calculateCloseIconTouchBounds(getBounds(), bounds);
}
/** Returns the width at which the chip would like to be laid out. */
@Override
public int getIntrinsicWidth() {
int calculatedWidth =
Math.round(
(chipStartPadding
+ calculateChipIconWidth()
+ textStartPadding
+ textDrawableHelper.getTextWidth(getText().toString())
+ textEndPadding
+ calculateCloseIconWidth()
+ chipEndPadding));
return Math.min(calculatedWidth, maxWidth);
}
/** Returns the height at which the chip would like to be laid out. */
@Override
public int getIntrinsicHeight() {
return (int) chipMinHeight;
}
/** Returns whether we will show the chip icon. */
private boolean showsChipIcon() {
return chipIconVisible && chipIcon != null;
}
/** Returns whether we will show the checked icon. */
private boolean showsCheckedIcon() {
return checkedIconVisible && checkedIcon != null && currentChecked;
}
/** Returns whether we will show the close icon. */
private boolean showsCloseIcon() {
return closeIconVisible && closeIcon != null;
}
/** Returns whether we can show the checked icon if our drawable state changes. */
private boolean canShowCheckedIcon() {
return checkedIconVisible && checkedIcon != null && checkable;
}
/** Returns the width of the chip icon plus padding, which only apply if the chip icon exists. */
float calculateChipIconWidth() {
if (showsChipIcon() || (showsCheckedIcon())) {
return iconStartPadding + getCurrentChipIconWidth() + iconEndPadding;
}
return 0f;
}
/**
* Return the chip's leading icon width. If chipIconSize > 0, return chipIconSize, else, return
* the current icon drawable width.
*/
private float getCurrentChipIconWidth() {
Drawable iconDrawable = currentChecked ? checkedIcon : chipIcon;
if (chipIconSize <= 0 && iconDrawable != null) {
return iconDrawable.getIntrinsicWidth();
}
return chipIconSize;
}
/**
* Return the chip's leading icon height. If chipIconSize > 0, return chipIconSize, else, return
* the current icon drawable height up to MAX_CHIP_ICON_HEIGHT
*/
private float getCurrentChipIconHeight() {
Drawable icon = currentChecked ? checkedIcon : chipIcon;
if (chipIconSize <= 0 && icon != null) {
float maxChipIconHeight = (float) Math.ceil(ViewUtils.dpToPx(context, MAX_CHIP_ICON_HEIGHT));
if (icon.getIntrinsicHeight() <= maxChipIconHeight) {
return icon.getIntrinsicHeight();
} else {
return maxChipIconHeight;
}
}
return chipIconSize;
}
/**
* Returns the width of the chip close icon plus padding, which only apply if the chip close icon
* exists.
*/
float calculateCloseIconWidth() {
if (showsCloseIcon()) {
return closeIconStartPadding + closeIconSize + closeIconEndPadding;
}
return 0f;
}
boolean isShapeThemingEnabled() {
return isShapeThemingEnabled;
}
@Override
public void draw(@NonNull Canvas canvas) {
Rect bounds = getBounds();
if (bounds.isEmpty() || getAlpha() == 0) {
return;
}
int saveCount = 0;
if (alpha < 255) {
saveCount =
CanvasCompat.saveLayerAlpha(
canvas, bounds.left, bounds.top, bounds.right, bounds.bottom, alpha);
}
// 0. Draw 100% opaque surface layer underneath partial transparent background.
drawChipSurface(canvas, bounds);
// 1. Draw chip background.
drawChipBackground(canvas, bounds);
if (isShapeThemingEnabled) {
super.draw(canvas);
}
// 2. Draw chip stroke.
drawChipStroke(canvas, bounds);
// 3. Draw compat ripple.
drawCompatRipple(canvas, bounds);
// 4. Draw chip icon.
drawChipIcon(canvas, bounds);
// 5. Draw checked icon.
drawCheckedIcon(canvas, bounds);
// 6. Draw chip text.
if (shouldDrawText) {
drawText(canvas, bounds);
}
// 7. Draw close icon.
drawCloseIcon(canvas, bounds);
// Debug.
drawDebug(canvas, bounds);
if (alpha < 255) {
canvas.restoreToCount(saveCount);
}
}
private void drawChipSurface(@NonNull Canvas canvas, @NonNull Rect bounds) {
if (!isShapeThemingEnabled) {
chipPaint.setColor(currentChipSurfaceColor);
chipPaint.setStyle(Style.FILL);
rectF.set(bounds);
canvas.drawRoundRect(rectF, getChipCornerRadius(), getChipCornerRadius(), chipPaint);
}
}
private void drawChipBackground(@NonNull Canvas canvas, @NonNull Rect bounds) {
if (!isShapeThemingEnabled) {
chipPaint.setColor(currentChipBackgroundColor);
chipPaint.setStyle(Style.FILL);
chipPaint.setColorFilter(getTintColorFilter());
rectF.set(bounds);
canvas.drawRoundRect(rectF, getChipCornerRadius(), getChipCornerRadius(), chipPaint);
}
}
/**
* Draws the chip stroke. Draw the stroke <code>chipStrokeWidth / 2f</code> away from the edges so
* that the stroke perfectly fills the bounds of the chip.
*/
private void drawChipStroke(@NonNull Canvas canvas, @NonNull Rect bounds) {
if (chipStrokeWidth > 0 && !isShapeThemingEnabled) {
chipPaint.setColor(currentChipStrokeColor);
chipPaint.setStyle(Style.STROKE);
if (!isShapeThemingEnabled) {
chipPaint.setColorFilter(getTintColorFilter());
}
rectF.set(
bounds.left + chipStrokeWidth / 2f,
bounds.top + chipStrokeWidth / 2f,
bounds.right - chipStrokeWidth / 2f,
bounds.bottom - chipStrokeWidth / 2f);
// We need to adjust stroke's corner radius so that the corners of the background are not
// drawn outside stroke
float strokeCornerRadius = chipCornerRadius - chipStrokeWidth / 2f;
canvas.drawRoundRect(rectF, strokeCornerRadius, strokeCornerRadius, chipPaint);
}
}
private void drawCompatRipple(@NonNull Canvas canvas, @NonNull Rect bounds) {
chipPaint.setColor(currentCompatRippleColor);
chipPaint.setStyle(Style.FILL);
rectF.set(bounds);
if (!isShapeThemingEnabled) {
canvas.drawRoundRect(rectF, getChipCornerRadius(), getChipCornerRadius(), chipPaint);
} else {
calculatePathForSize(new RectF(bounds), shapePath);
super.drawShape(canvas, chipPaint, shapePath, getBoundsAsRectF());
}
}
private void drawChipIcon(@NonNull Canvas canvas, @NonNull Rect bounds) {
if (showsChipIcon()) {
calculateChipIconBounds(bounds, rectF);
float tx = rectF.left;
float ty = rectF.top;
canvas.translate(tx, ty);
chipIcon.setBounds(0, 0, (int) rectF.width(), (int) rectF.height());
chipIcon.draw(canvas);
canvas.translate(-tx, -ty);
}
}
private void drawCheckedIcon(@NonNull Canvas canvas, @NonNull Rect bounds) {
if (showsCheckedIcon()) {
calculateChipIconBounds(bounds, rectF);
float tx = rectF.left;
float ty = rectF.top;
canvas.translate(tx, ty);
checkedIcon.setBounds(0, 0, (int) rectF.width(), (int) rectF.height());
checkedIcon.draw(canvas);
canvas.translate(-tx, -ty);
}
}
/** Draws the chip text, which should appear centered vertically in the chip. */
private void drawText(@NonNull Canvas canvas, @NonNull Rect bounds) {
if (text != null) {
Align align = calculateTextOriginAndAlignment(bounds, pointF);
// If bounds are smaller than intrinsic size. Ellipsize or clip the text depending on
// ellipsize attribute.
calculateTextBounds(bounds, rectF);
if (textDrawableHelper.getTextAppearance() != null) {
textDrawableHelper.getTextPaint().drawableState = getState();
textDrawableHelper.updateTextPaintDrawState(context);
}
textDrawableHelper.getTextPaint().setTextAlign(align);
boolean clip =
Math.round(textDrawableHelper.getTextWidth(getText().toString()))
> Math.round(rectF.width());
int saveCount = 0;
if (clip) {
saveCount = canvas.save();
canvas.clipRect(rectF);
}
CharSequence finalText = text;
if (clip && truncateAt != null) {
finalText =
TextUtils.ellipsize(text, textDrawableHelper.getTextPaint(), rectF.width(), truncateAt);
}
canvas.drawText(
finalText, 0, finalText.length(), pointF.x, pointF.y, textDrawableHelper.getTextPaint());
if (clip) {
canvas.restoreToCount(saveCount);
}
}
}
private void drawCloseIcon(@NonNull Canvas canvas, @NonNull Rect bounds) {
if (showsCloseIcon()) {
calculateCloseIconBounds(bounds, rectF);
float tx = rectF.left;
float ty = rectF.top;
canvas.translate(tx, ty);
closeIcon.setBounds(0, 0, (int) rectF.width(), (int) rectF.height());
if (RippleUtils.USE_FRAMEWORK_RIPPLE) {
closeIconRipple.setBounds(closeIcon.getBounds());
closeIconRipple.jumpToCurrentState();
closeIconRipple.draw(canvas);
} else {
closeIcon.draw(canvas);
}
canvas.translate(-tx, -ty);
}
}
private void drawDebug(@NonNull Canvas canvas, @NonNull Rect bounds) {
if (debugPaint != null) {
debugPaint.setColor(ColorUtils.setAlphaComponent(Color.BLACK, 255 / 2));
// Background.
canvas.drawRect(bounds, debugPaint);
// Chip and checked icon.
if (showsChipIcon() || (showsCheckedIcon())) {
calculateChipIconBounds(bounds, rectF);
canvas.drawRect(rectF, debugPaint);
}
// Chip text.
if (text != null) {
canvas.drawLine(
bounds.left, bounds.exactCenterY(), bounds.right, bounds.exactCenterY(), debugPaint);
}
// Close icon.
if (showsCloseIcon()) {
calculateCloseIconBounds(bounds, rectF);
canvas.drawRect(rectF, debugPaint);
}
// Chip touch bounds.
debugPaint.setColor(ColorUtils.setAlphaComponent(Color.RED, 255 / 2));
calculateChipTouchBounds(bounds, rectF);
canvas.drawRect(rectF, debugPaint);
// Close icon touch bounds.
debugPaint.setColor(ColorUtils.setAlphaComponent(Color.GREEN, 255 / 2));
calculateCloseIconTouchBounds(bounds, rectF);
canvas.drawRect(rectF, debugPaint);
}
}
/**
* Calculates the chip icon's ChipDrawable-absolute bounds (top-left is <code>
* [ChipDrawable.getBounds().left, ChipDrawable.getBounds().top]</code>).
*/
private void calculateChipIconBounds(@NonNull Rect bounds, @NonNull RectF outBounds) {
outBounds.setEmpty();
if (showsChipIcon() || showsCheckedIcon()) {
float offsetFromStart = chipStartPadding + iconStartPadding;
float chipWidth = getCurrentChipIconWidth();
if (DrawableCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_LTR) {
outBounds.left = bounds.left + offsetFromStart;
outBounds.right = outBounds.left + chipWidth;
} else {
outBounds.right = bounds.right - offsetFromStart;
outBounds.left = outBounds.right - chipWidth;
}
float chipHeight = getCurrentChipIconHeight();
outBounds.top = bounds.exactCenterY() - chipHeight / 2f;
outBounds.bottom = outBounds.top + chipHeight;
}
}
/** Calculates the chip text's origin and alignment based on the ChipDrawable-absolute bounds. */
@NonNull
Align calculateTextOriginAndAlignment(@NonNull Rect bounds, @NonNull PointF pointF) {
pointF.set(0, 0);
Align align = Align.LEFT;
if (text != null) {
float offsetFromStart = chipStartPadding + calculateChipIconWidth() + textStartPadding;
if (DrawableCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_LTR) {
pointF.x = bounds.left + offsetFromStart;
align = Align.LEFT;
} else {
pointF.x = bounds.right - offsetFromStart;
align = Align.RIGHT;
}
pointF.y = bounds.centerY() - calculateTextCenterFromBaseline();
}
return align;
}
/**
* Calculates the offset from the visual center of the chip text to its baseline.
*
* <p>To draw the chip text, we provide the origin to {@link Canvas#drawText(CharSequence, int,
* int, float, float, Paint)}. This origin always corresponds vertically to the text's baseline.
* Because we need to vertically center the text, we need to calculate this offset.
*
* <p>Note that chips that share the same font must have consistent text baselines despite having
* different text strings. This is why we calculate the vertical center using {@link
* Paint#getFontMetrics(FontMetrics)} rather than {@link Paint#getTextBounds(String, int, int,
* Rect)}.
*/
private float calculateTextCenterFromBaseline() {
textDrawableHelper.getTextPaint().getFontMetrics(fontMetrics);
return (fontMetrics.descent + fontMetrics.ascent) / 2f;
}
/**
* Calculates the chip text's ChipDrawable-absolute bounds (top-left is <code>
* [ChipDrawable.getBounds().left, ChipDrawable.getBounds().top]</code>).
*/
private void calculateTextBounds(@NonNull Rect bounds, @NonNull RectF outBounds) {
outBounds.setEmpty();
if (text != null) {
float offsetFromStart = chipStartPadding + calculateChipIconWidth() + textStartPadding;
float offsetFromEnd = chipEndPadding + calculateCloseIconWidth() + textEndPadding;
if (DrawableCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_LTR) {
outBounds.left = bounds.left + offsetFromStart;
outBounds.right = bounds.right - offsetFromEnd;
} else {
outBounds.left = bounds.left + offsetFromEnd;
outBounds.right = bounds.right - offsetFromStart;
}
// Top and bottom included for completion. Don't position the chip text vertically based on
// these bounds. Instead, use #calculateTextOriginAndAlignment().
outBounds.top = bounds.top;
outBounds.bottom = bounds.bottom;
}
}
/**
* Calculates the close icon's ChipDrawable-absolute bounds (top-left is <code>
* [ChipDrawable.getBounds().left, ChipDrawable.getBounds().top]</code>).
*/
private void calculateCloseIconBounds(@NonNull Rect bounds, @NonNull RectF outBounds) {
outBounds.setEmpty();
if (showsCloseIcon()) {
float offsetFromEnd = chipEndPadding + closeIconEndPadding;
if (DrawableCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_LTR) {
outBounds.right = bounds.right - offsetFromEnd;
outBounds.left = outBounds.right - closeIconSize;
} else {
outBounds.left = bounds.left + offsetFromEnd;
outBounds.right = outBounds.left + closeIconSize;
}
outBounds.top = bounds.exactCenterY() - closeIconSize / 2f;
outBounds.bottom = outBounds.top + closeIconSize;
}
}
private void calculateChipTouchBounds(@NonNull Rect bounds, @NonNull RectF outBounds) {
outBounds.set(bounds);
if (showsCloseIcon()) {
float offsetFromEnd =
chipEndPadding
+ closeIconEndPadding
+ closeIconSize
+ closeIconStartPadding
+ textEndPadding;
if (DrawableCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_LTR) {
outBounds.right = bounds.right - offsetFromEnd;
} else {
outBounds.left = bounds.left + offsetFromEnd;
}
}
}
private void calculateCloseIconTouchBounds(@NonNull Rect bounds, @NonNull RectF outBounds) {
outBounds.setEmpty();
if (showsCloseIcon()) {
float offsetFromEnd =
chipEndPadding
+ closeIconEndPadding
+ closeIconSize
+ closeIconStartPadding
+ textEndPadding;
if (DrawableCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_LTR) {
outBounds.right = bounds.right;
outBounds.left = outBounds.right - offsetFromEnd;
} else {
outBounds.left = bounds.left;
outBounds.right = bounds.left + offsetFromEnd;
}
outBounds.top = bounds.top;
outBounds.bottom = bounds.bottom;
}
}
/** Indicates whether this chip drawable will change its appearance based on state. */
@Override
public boolean isStateful() {
// The logic here and #isCloseIconStateful() must match #onStateChange(int[],int[]).
return isStateful(chipSurfaceColor)
|| isStateful(chipBackgroundColor)
|| isStateful(chipStrokeColor)
|| (useCompatRipple && isStateful(compatRippleColor))
|| isStateful(textDrawableHelper.getTextAppearance())
|| canShowCheckedIcon()
|| isStateful(chipIcon)
|| isStateful(checkedIcon)
|| isStateful(tint);
}
/** Indicates whether the close icon drawable will change its appearance based on state. */
public boolean isCloseIconStateful() {
// The logic here and #isStateful() must match #onStateChange(int[], int[]).
return isStateful(closeIcon);
}
/**
* Specify a set of states for the close icon. This is a separate state set than the one used for
* the rest of the chip.
*/
public boolean setCloseIconState(@NonNull int[] stateSet) {
if (!Arrays.equals(closeIconStateSet, stateSet)) {
closeIconStateSet = stateSet;
if (showsCloseIcon()) {
return onStateChange(getState(), stateSet);
}
}
return false;
}