-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathCollapsingTextHelper.java
1351 lines (1176 loc) · 46.4 KB
/
CollapsingTextHelper.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 (C) 2015 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.internal;
import static android.text.Layout.Alignment.ALIGN_CENTER;
import static android.text.Layout.Alignment.ALIGN_NORMAL;
import static android.text.Layout.Alignment.ALIGN_OPPOSITE;
import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP;
import static androidx.core.util.Preconditions.checkNotNull;
import static java.lang.Math.max;
import static java.lang.Math.min;
import android.animation.TimeInterpolator;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.text.Layout.Alignment;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import androidx.annotation.ColorInt;
import androidx.annotation.FloatRange;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.annotation.RestrictTo;
import androidx.core.math.MathUtils;
import androidx.core.text.TextDirectionHeuristicsCompat;
import com.google.android.material.animation.AnimationUtils;
import com.google.android.material.color.MaterialColors;
import com.google.android.material.internal.StaticLayoutBuilderCompat.StaticLayoutBuilderCompatException;
import com.google.android.material.resources.CancelableFontCallback;
import com.google.android.material.resources.CancelableFontCallback.ApplyFont;
import com.google.android.material.resources.TextAppearance;
import com.google.android.material.resources.TypefaceUtils;
/**
* Helper class for rendering and animating collapsed text.
*
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
public final class CollapsingTextHelper {
private static final String TAG = "CollapsingTextHelper";
private static final String ELLIPSIS_NORMAL = "\u2026"; // HORIZONTAL ELLIPSIS (...)
private static final float FADE_MODE_THRESHOLD_FRACTION_RELATIVE = 0.5f;
private static final boolean DEBUG_DRAW = false;
@Nullable private static final Paint DEBUG_DRAW_PAINT;
public static final int SEMITRANSPARENT_MAGENTA = 0x40FF00FF;
static {
DEBUG_DRAW_PAINT = DEBUG_DRAW ? new Paint() : null;
if (DEBUG_DRAW_PAINT != null) {
DEBUG_DRAW_PAINT.setAntiAlias(true);
DEBUG_DRAW_PAINT.setColor(SEMITRANSPARENT_MAGENTA);
}
}
private final View view;
private float expandedFraction;
private boolean fadeModeEnabled;
private float fadeModeStartFraction;
private float fadeModeThresholdFraction;
private int currentOffsetY;
@NonNull private final Rect expandedBounds;
@NonNull private final Rect collapsedBounds;
@NonNull private final RectF currentBounds;
private int expandedTextGravity = Gravity.CENTER_VERTICAL;
private int collapsedTextGravity = Gravity.CENTER_VERTICAL;
private float expandedTextSize = 15;
private float collapsedTextSize = 15;
private ColorStateList expandedTextColor;
private ColorStateList collapsedTextColor;
private int expandedLineCount;
private float expandedDrawY;
private float collapsedDrawY;
private float expandedDrawX;
private float collapsedDrawX;
private float currentDrawX;
private float currentDrawY;
private Typeface collapsedTypeface;
private Typeface collapsedTypefaceBold;
private Typeface collapsedTypefaceDefault;
private Typeface expandedTypeface;
private Typeface expandedTypefaceBold;
private Typeface expandedTypefaceDefault;
private Typeface currentTypeface;
private CancelableFontCallback expandedFontCallback;
private CancelableFontCallback collapsedFontCallback;
private TruncateAt titleTextEllipsize = TruncateAt.END;
@Nullable private CharSequence text;
@Nullable private CharSequence textToDraw;
private boolean isRtl;
private boolean isRtlTextDirectionHeuristicsEnabled = true;
private float scale;
private float currentTextSize;
private float currentShadowRadius;
private float currentShadowDx;
private float currentShadowDy;
private int currentShadowColor;
private int currentMaxLines;
private int[] state;
private boolean boundsChanged;
@NonNull private final TextPaint textPaint;
@NonNull private final TextPaint tmpPaint;
private TimeInterpolator positionInterpolator;
private TimeInterpolator textSizeInterpolator;
private float collapsedShadowRadius;
private float collapsedShadowDx;
private float collapsedShadowDy;
private ColorStateList collapsedShadowColor;
private float expandedShadowRadius;
private float expandedShadowDx;
private float expandedShadowDy;
private ColorStateList expandedShadowColor;
private float collapsedLetterSpacing;
private float expandedLetterSpacing;
private float currentLetterSpacing;
private StaticLayout textLayout;
private float collapsedTextWidth;
private float collapsedTextBlend;
private float expandedTextBlend;
private CharSequence textToDrawCollapsed;
private static final int ONE_LINE = 1;
private int expandedMaxLines = ONE_LINE;
private int collapsedMaxLines = ONE_LINE;
private float lineSpacingAdd = StaticLayoutBuilderCompat.DEFAULT_LINE_SPACING_ADD;
private float lineSpacingMultiplier = StaticLayoutBuilderCompat.DEFAULT_LINE_SPACING_MULTIPLIER;
private int hyphenationFrequency = StaticLayoutBuilderCompat.DEFAULT_HYPHENATION_FREQUENCY;
@Nullable private StaticLayoutBuilderConfigurer staticLayoutBuilderConfigurer;
private int collapsedHeight = -1;
private int expandedHeight = -1;
private boolean alignBaselineAtBottom;
public CollapsingTextHelper(View view) {
this.view = view;
textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);
tmpPaint = new TextPaint(textPaint);
collapsedBounds = new Rect();
expandedBounds = new Rect();
currentBounds = new RectF();
fadeModeThresholdFraction = calculateFadeModeThresholdFraction();
maybeUpdateFontWeightAdjustment(view.getContext().getResources().getConfiguration());
}
public void setCollapsedMaxLines(int collapsedMaxLines) {
if (collapsedMaxLines != this.collapsedMaxLines) {
this.collapsedMaxLines = collapsedMaxLines;
recalculate();
}
}
public void setTextSizeInterpolator(TimeInterpolator interpolator) {
textSizeInterpolator = interpolator;
recalculate();
}
public void setPositionInterpolator(TimeInterpolator interpolator) {
positionInterpolator = interpolator;
recalculate();
}
@Nullable
public TimeInterpolator getPositionInterpolator() {
return positionInterpolator;
}
public void setExpandedTextSize(float textSize) {
if (expandedTextSize != textSize) {
expandedTextSize = textSize;
recalculate();
}
}
public void setCollapsedTextSize(float textSize) {
if (collapsedTextSize != textSize) {
collapsedTextSize = textSize;
recalculate();
}
}
public void setCollapsedTextColor(ColorStateList textColor) {
if (collapsedTextColor != textColor) {
collapsedTextColor = textColor;
recalculate();
}
}
public void setExpandedTextColor(ColorStateList textColor) {
if (expandedTextColor != textColor) {
expandedTextColor = textColor;
recalculate();
}
}
public void setCollapsedAndExpandedTextColor(@Nullable ColorStateList textColor) {
if (collapsedTextColor != textColor || expandedTextColor != textColor) {
collapsedTextColor = textColor;
expandedTextColor = textColor;
recalculate();
}
}
public void setExpandedLetterSpacing(float letterSpacing) {
if (expandedLetterSpacing != letterSpacing) {
expandedLetterSpacing = letterSpacing;
recalculate();
}
}
public void setExpandedBounds(
int left, int top, int right, int bottom, boolean alignBaselineAtBottom) {
if (!rectEquals(expandedBounds, left, top, right, bottom)
|| alignBaselineAtBottom != this.alignBaselineAtBottom) {
expandedBounds.set(left, top, right, bottom);
boundsChanged = true;
this.alignBaselineAtBottom = alignBaselineAtBottom;
}
}
public void setExpandedBounds(int left, int top, int right, int bottom) {
setExpandedBounds(left, top, right, bottom, /* alignBaselineAtBottom= */ true);
}
public void setExpandedBounds(@NonNull Rect bounds) {
setExpandedBounds(bounds.left, bounds.top, bounds.right, bounds.bottom);
}
public void setCollapsedBounds(int left, int top, int right, int bottom) {
if (!rectEquals(collapsedBounds, left, top, right, bottom)) {
collapsedBounds.set(left, top, right, bottom);
boundsChanged = true;
}
}
public void setCollapsedBounds(@NonNull Rect bounds) {
setCollapsedBounds(bounds.left, bounds.top, bounds.right, bounds.bottom);
}
public void getCollapsedTextBottomTextBounds(
@NonNull RectF bounds, int labelWidth, int textGravity) {
isRtl = calculateIsRtl(text);
bounds.left = max(getCollapsedTextLeftBound(labelWidth, textGravity), collapsedBounds.left);
bounds.top = collapsedBounds.top;
bounds.right =
min(getCollapsedTextRightBound(bounds, labelWidth, textGravity), collapsedBounds.right);
bounds.bottom = collapsedBounds.top + getCollapsedTextHeight();
if (textLayout != null && !shouldTruncateCollapsedToSingleLine()) {
// If the text is not truncated to one line when collapsed, we want to return the width of the
// bottommost line, which is the textLayout's line width * the scale factor of the expanded
// text size to the collapsed text size.
float lineWidth =
textLayout.getLineWidth(textLayout.getLineCount() - 1)
* (collapsedTextSize / expandedTextSize);
if (isRtl) {
bounds.left = bounds.right - lineWidth;
} else {
bounds.right = bounds.left + lineWidth;
}
}
}
private float getCollapsedTextLeftBound(int width, int gravity) {
if (gravity == Gravity.CENTER
|| (gravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.CENTER_HORIZONTAL) {
return width / 2f - collapsedTextWidth / 2;
} else if ((gravity & Gravity.END) == Gravity.END
|| (gravity & Gravity.RIGHT) == Gravity.RIGHT) {
return isRtl ? collapsedBounds.left : (collapsedBounds.right - collapsedTextWidth);
} else {
return isRtl ? (collapsedBounds.right - collapsedTextWidth) : collapsedBounds.left;
}
}
private float getCollapsedTextRightBound(@NonNull RectF bounds, int width, int gravity) {
if (gravity == Gravity.CENTER
|| (gravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.CENTER_HORIZONTAL) {
return width / 2f + collapsedTextWidth / 2;
} else if ((gravity & Gravity.END) == Gravity.END
|| (gravity & Gravity.RIGHT) == Gravity.RIGHT) {
return isRtl ? (bounds.left + collapsedTextWidth) : collapsedBounds.right;
} else {
return isRtl ? collapsedBounds.right : (bounds.left + collapsedTextWidth);
}
}
public float getExpandedTextSingleLineHeight() {
getTextPaintExpanded(tmpPaint);
// Return expanded height measured from the baseline.
return -tmpPaint.ascent();
}
public float getExpandedTextFullSingleLineHeight() {
getTextPaintExpanded(tmpPaint);
// Return expanded height measured from the baseline.
return -tmpPaint.ascent() + tmpPaint.descent();
}
public void updateTextHeights(int availableWidth) {
// Set collapsed height
getTextPaintCollapsed(tmpPaint);
StaticLayout textLayout =
createStaticLayout(
collapsedMaxLines,
tmpPaint,
text,
availableWidth * (collapsedTextSize / expandedTextSize),
isRtl);
collapsedHeight = textLayout.getHeight();
// Set expanded height
getTextPaintExpanded(tmpPaint);
textLayout = createStaticLayout(expandedMaxLines, tmpPaint, text, availableWidth, isRtl);
expandedHeight = textLayout.getHeight();
}
public float getCollapsedTextHeight() {
return collapsedHeight != -1 ? collapsedHeight : getCollapsedSingleLineHeight();
}
public float getExpandedTextHeight() {
return expandedHeight != -1 ? expandedHeight : getExpandedTextSingleLineHeight();
}
public float getCollapsedSingleLineHeight() {
getTextPaintCollapsed(tmpPaint);
// Return collapsed height measured from the baseline.
return -tmpPaint.ascent();
}
public float getCollapsedFullSingleLineHeight() {
getTextPaintCollapsed(tmpPaint);
// Return collapsed height measured from the baseline.
return -tmpPaint.ascent() + tmpPaint.descent();
}
public void setCurrentOffsetY(int currentOffsetY) {
this.currentOffsetY = currentOffsetY;
}
public void setFadeModeStartFraction(float fadeModeStartFraction) {
this.fadeModeStartFraction = fadeModeStartFraction;
fadeModeThresholdFraction = calculateFadeModeThresholdFraction();
}
private float calculateFadeModeThresholdFraction() {
return fadeModeStartFraction
+ (1 - fadeModeStartFraction) * FADE_MODE_THRESHOLD_FRACTION_RELATIVE;
}
public void setFadeModeEnabled(boolean fadeModeEnabled) {
this.fadeModeEnabled = fadeModeEnabled;
}
private void getTextPaintExpanded(@NonNull TextPaint textPaint) {
textPaint.setTextSize(expandedTextSize);
textPaint.setTypeface(expandedTypeface);
textPaint.setLetterSpacing(expandedLetterSpacing);
}
private void getTextPaintCollapsed(@NonNull TextPaint textPaint) {
textPaint.setTextSize(collapsedTextSize);
textPaint.setTypeface(collapsedTypeface);
textPaint.setLetterSpacing(collapsedLetterSpacing);
}
public void setExpandedTextGravity(int gravity) {
if (expandedTextGravity != gravity) {
expandedTextGravity = gravity;
recalculate();
}
}
public int getExpandedTextGravity() {
return expandedTextGravity;
}
public void setCollapsedTextGravity(int gravity) {
if (collapsedTextGravity != gravity) {
collapsedTextGravity = gravity;
recalculate();
}
}
public int getCollapsedTextGravity() {
return collapsedTextGravity;
}
public void setCollapsedTextAppearance(int resId) {
TextAppearance textAppearance = new TextAppearance(view.getContext(), resId);
if (textAppearance.getTextColor() != null) {
collapsedTextColor = textAppearance.getTextColor();
}
if (textAppearance.getTextSize() != 0) {
collapsedTextSize = textAppearance.getTextSize();
}
if (textAppearance.shadowColor != null) {
collapsedShadowColor = textAppearance.shadowColor;
}
collapsedShadowDx = textAppearance.shadowDx;
collapsedShadowDy = textAppearance.shadowDy;
collapsedShadowRadius = textAppearance.shadowRadius;
collapsedLetterSpacing = textAppearance.letterSpacing;
// Cancel pending async fetch, if any, and replace with a new one.
if (collapsedFontCallback != null) {
collapsedFontCallback.cancel();
}
collapsedFontCallback =
new CancelableFontCallback(
new ApplyFont() {
@Override
public void apply(Typeface font) {
setCollapsedTypeface(font);
}
},
textAppearance.getFallbackFont());
textAppearance.getFontAsync(view.getContext(), collapsedFontCallback);
recalculate();
}
public void setExpandedTextAppearance(int resId) {
TextAppearance textAppearance = new TextAppearance(view.getContext(), resId);
if (textAppearance.getTextColor() != null) {
expandedTextColor = textAppearance.getTextColor();
}
if (textAppearance.getTextSize() != 0) {
expandedTextSize = textAppearance.getTextSize();
}
if (textAppearance.shadowColor != null) {
expandedShadowColor = textAppearance.shadowColor;
}
expandedShadowDx = textAppearance.shadowDx;
expandedShadowDy = textAppearance.shadowDy;
expandedShadowRadius = textAppearance.shadowRadius;
expandedLetterSpacing = textAppearance.letterSpacing;
// Cancel pending async fetch, if any, and replace with a new one.
if (expandedFontCallback != null) {
expandedFontCallback.cancel();
}
expandedFontCallback =
new CancelableFontCallback(
new ApplyFont() {
@Override
public void apply(Typeface font) {
setExpandedTypeface(font);
}
},
textAppearance.getFallbackFont());
textAppearance.getFontAsync(view.getContext(), expandedFontCallback);
recalculate();
}
public void setTitleTextEllipsize(@NonNull TruncateAt ellipsize) {
titleTextEllipsize = ellipsize;
recalculate();
}
@NonNull
public TruncateAt getTitleTextEllipsize() {
return titleTextEllipsize;
}
public void setCollapsedTypeface(Typeface typeface) {
if (setCollapsedTypefaceInternal(typeface)) {
recalculate();
}
}
public void setExpandedTypeface(Typeface typeface) {
if (setExpandedTypefaceInternal(typeface)) {
recalculate();
}
}
public void setTypefaces(Typeface typeface) {
boolean collapsedFontChanged = setCollapsedTypefaceInternal(typeface);
boolean expandedFontChanged = setExpandedTypefaceInternal(typeface);
if (collapsedFontChanged || expandedFontChanged) {
recalculate();
}
}
@SuppressWarnings("ReferenceEquality") // Matches the Typeface comparison in TextView
private boolean setCollapsedTypefaceInternal(Typeface typeface) {
// Explicit Typeface setting cancels pending async fetch, if any, to avoid old font overriding
// already updated one when async op comes back after a while.
if (collapsedFontCallback != null) {
collapsedFontCallback.cancel();
}
if (collapsedTypefaceDefault != typeface) {
collapsedTypefaceDefault = typeface;
collapsedTypefaceBold =
TypefaceUtils.maybeCopyWithFontWeightAdjustment(
view.getContext().getResources().getConfiguration(), typeface);
collapsedTypeface =
collapsedTypefaceBold == null ? collapsedTypefaceDefault : collapsedTypefaceBold;
return true;
}
return false;
}
@SuppressWarnings("ReferenceEquality") // Matches the Typeface comparison in TextView
private boolean setExpandedTypefaceInternal(Typeface typeface) {
// Explicit Typeface setting cancels pending async fetch, if any, to avoid old font overriding
// already updated one when async op comes back after a while.
if (expandedFontCallback != null) {
expandedFontCallback.cancel();
}
if (expandedTypefaceDefault != typeface) {
expandedTypefaceDefault = typeface;
expandedTypefaceBold =
TypefaceUtils.maybeCopyWithFontWeightAdjustment(
view.getContext().getResources().getConfiguration(), typeface);
expandedTypeface =
expandedTypefaceBold == null ? expandedTypefaceDefault : expandedTypefaceBold;
return true;
}
return false;
}
public Typeface getCollapsedTypeface() {
return collapsedTypeface != null ? collapsedTypeface : Typeface.DEFAULT;
}
public Typeface getExpandedTypeface() {
return expandedTypeface != null ? expandedTypeface : Typeface.DEFAULT;
}
public void maybeUpdateFontWeightAdjustment(@NonNull Configuration configuration) {
if (VERSION.SDK_INT >= VERSION_CODES.S) {
if (collapsedTypefaceDefault != null) {
collapsedTypefaceBold =
TypefaceUtils.maybeCopyWithFontWeightAdjustment(
configuration, collapsedTypefaceDefault);
}
if (expandedTypefaceDefault != null) {
expandedTypefaceBold =
TypefaceUtils.maybeCopyWithFontWeightAdjustment(configuration, expandedTypefaceDefault);
}
collapsedTypeface =
collapsedTypefaceBold != null ? collapsedTypefaceBold : collapsedTypefaceDefault;
expandedTypeface =
expandedTypefaceBold != null ? expandedTypefaceBold : expandedTypefaceDefault;
recalculate(/* forceRecalculate= */ true);
}
}
/**
* Set the value indicating the current scroll value. This decides how much of the background will
* be displayed, as well as the title metrics/positioning.
*
* <p>A value of {@code 0.0} indicates that the layout is fully expanded. A value of {@code 1.0}
* indicates that the layout is fully collapsed.
*/
public void setExpansionFraction(float fraction) {
fraction = MathUtils.clamp(fraction, 0f, 1f);
if (fraction != expandedFraction) {
expandedFraction = fraction;
calculateCurrentOffsets();
}
}
public final boolean setState(final int[] state) {
this.state = state;
if (isStateful()) {
recalculate();
return true;
}
return false;
}
public final boolean isStateful() {
return (collapsedTextColor != null && collapsedTextColor.isStateful())
|| (expandedTextColor != null && expandedTextColor.isStateful());
}
public float getFadeModeThresholdFraction() {
return fadeModeThresholdFraction;
}
public float getExpansionFraction() {
return expandedFraction;
}
public float getCollapsedTextSize() {
return collapsedTextSize;
}
public float getExpandedTextSize() {
return expandedTextSize;
}
public void setRtlTextDirectionHeuristicsEnabled(boolean rtlTextDirectionHeuristicsEnabled) {
isRtlTextDirectionHeuristicsEnabled = rtlTextDirectionHeuristicsEnabled;
}
public boolean isRtlTextDirectionHeuristicsEnabled() {
return isRtlTextDirectionHeuristicsEnabled;
}
private void calculateCurrentOffsets() {
calculateOffsets(expandedFraction);
}
private void calculateOffsets(final float fraction) {
interpolateBounds(fraction);
float textBlendFraction;
if (fadeModeEnabled) {
if (fraction < fadeModeThresholdFraction) {
textBlendFraction = 0F;
currentDrawX = expandedDrawX;
currentDrawY = expandedDrawY;
setInterpolatedTextSize(/* fraction= */ 0);
} else {
textBlendFraction = 1F;
currentDrawX = collapsedDrawX;
currentDrawY = collapsedDrawY - max(0, currentOffsetY);
setInterpolatedTextSize(/* fraction= */ 1);
}
} else {
textBlendFraction = fraction;
currentDrawX = lerp(expandedDrawX, collapsedDrawX, fraction, positionInterpolator);
currentDrawY = lerp(expandedDrawY, collapsedDrawY, fraction, positionInterpolator);
setInterpolatedTextSize(fraction);
}
setCollapsedTextBlend(
1 - lerp(0, 1, 1 - fraction, AnimationUtils.FAST_OUT_SLOW_IN_INTERPOLATOR));
setExpandedTextBlend(lerp(1, 0, fraction, AnimationUtils.FAST_OUT_SLOW_IN_INTERPOLATOR));
if (collapsedTextColor != expandedTextColor) {
// If the collapsed and expanded text colors are different, blend them based on the
// fraction
textPaint.setColor(
blendARGB(
getCurrentExpandedTextColor(), getCurrentCollapsedTextColor(), textBlendFraction));
} else {
textPaint.setColor(getCurrentCollapsedTextColor());
}
// Calculates paint parameters for shadow layer.
currentShadowRadius = lerp(expandedShadowRadius, collapsedShadowRadius, fraction, null);
currentShadowDx = lerp(expandedShadowDx, collapsedShadowDx, fraction, null);
currentShadowDy = lerp(expandedShadowDy, collapsedShadowDy, fraction, null);
currentShadowColor =
blendARGB(
getCurrentColor(expandedShadowColor), getCurrentColor(collapsedShadowColor), fraction);
textPaint.setShadowLayer(
currentShadowRadius, currentShadowDx, currentShadowDy, currentShadowColor);
if (fadeModeEnabled) {
int originalAlpha = textPaint.getAlpha();
// Calculates new alpha as a ratio of original alpha based on position.
int textAlpha = (int) (calculateFadeModeTextAlpha(fraction) * originalAlpha);
textPaint.setAlpha(textAlpha);
// Workaround for API 31(+). Applying the shadow color for the painted text.
if (VERSION.SDK_INT >= VERSION_CODES.S) {
textPaint.setShadowLayer(
currentShadowRadius,
currentShadowDx,
currentShadowDy,
MaterialColors.compositeARGBWithAlpha(currentShadowColor, textPaint.getAlpha()));
}
}
view.postInvalidateOnAnimation();
}
private float calculateFadeModeTextAlpha(@FloatRange(from = 0.0, to = 1.0) float fraction) {
if (fraction <= fadeModeThresholdFraction) {
return AnimationUtils.lerp(
/* startValue= */ 1,
/* endValue= */ 0,
/* startFraction= */ fadeModeStartFraction,
/* endFraction= */ fadeModeThresholdFraction,
fraction);
} else {
return AnimationUtils.lerp(
/* startValue= */ 0,
/* endValue= */ 1,
/* startFraction= */ fadeModeThresholdFraction,
/* endFraction= */ 1,
fraction);
}
}
@ColorInt
private int getCurrentExpandedTextColor() {
return getCurrentColor(expandedTextColor);
}
@ColorInt
public int getCurrentCollapsedTextColor() {
return getCurrentColor(collapsedTextColor);
}
@ColorInt
private int getCurrentColor(@Nullable ColorStateList colorStateList) {
if (colorStateList == null) {
return 0;
}
if (state != null) {
return colorStateList.getColorForState(state, 0);
}
return colorStateList.getDefaultColor();
}
private boolean shouldTruncateCollapsedToSingleLine() {
return collapsedMaxLines == ONE_LINE;
}
private void calculateBaseOffsets(boolean forceRecalculate) {
// We then calculate the collapsed text size, using the same logic
calculateUsingTextSize(/* fraction= */ 1, forceRecalculate);
if (textToDraw != null && textLayout != null) {
textToDrawCollapsed = shouldTruncateCollapsedToSingleLine()
? TextUtils.ellipsize(
textToDraw, textPaint, textLayout.getWidth(), titleTextEllipsize)
: textToDraw;
}
if (textToDrawCollapsed != null) {
collapsedTextWidth = measureTextWidth(textPaint, textToDrawCollapsed);
} else {
collapsedTextWidth = 0;
}
final int collapsedAbsGravity =
Gravity.getAbsoluteGravity(
collapsedTextGravity,
isRtl ? View.LAYOUT_DIRECTION_RTL : View.LAYOUT_DIRECTION_LTR);
switch (collapsedAbsGravity & Gravity.VERTICAL_GRAVITY_MASK) {
case Gravity.BOTTOM:
collapsedDrawY = collapsedBounds.bottom + textPaint.ascent();
break;
case Gravity.TOP:
collapsedDrawY = collapsedBounds.top;
break;
case Gravity.CENTER_VERTICAL:
default:
float textOffset = (textPaint.descent() - textPaint.ascent()) / 2;
collapsedDrawY = collapsedBounds.centerY() - textOffset;
break;
}
switch (collapsedAbsGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) {
case Gravity.CENTER_HORIZONTAL:
collapsedDrawX = collapsedBounds.centerX() - (collapsedTextWidth / 2);
break;
case Gravity.RIGHT:
collapsedDrawX = collapsedBounds.right - collapsedTextWidth;
break;
case Gravity.LEFT:
default:
collapsedDrawX = collapsedBounds.left;
break;
}
calculateUsingTextSize(/* fraction= */ 0, forceRecalculate);
float expandedTextHeight = textLayout != null ? textLayout.getHeight() : 0;
float expandedTextWidth = 0;
if (textLayout != null && expandedMaxLines > 1) {
expandedTextWidth = textLayout.getWidth();
} else if (textToDraw != null) {
expandedTextWidth = measureTextWidth(textPaint, textToDraw);
}
expandedLineCount = textLayout != null ? textLayout.getLineCount() : 0;
final int expandedAbsGravity =
Gravity.getAbsoluteGravity(
expandedTextGravity,
isRtl ? View.LAYOUT_DIRECTION_RTL : View.LAYOUT_DIRECTION_LTR);
switch (expandedAbsGravity & Gravity.VERTICAL_GRAVITY_MASK) {
case Gravity.BOTTOM:
expandedDrawY =
expandedBounds.bottom
- expandedTextHeight
+ (alignBaselineAtBottom ? textPaint.descent() : 0);
break;
case Gravity.TOP:
expandedDrawY = expandedBounds.top;
break;
case Gravity.CENTER_VERTICAL:
default:
float textOffset = expandedTextHeight / 2;
expandedDrawY = expandedBounds.centerY() - textOffset;
break;
}
switch (expandedAbsGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) {
case Gravity.CENTER_HORIZONTAL:
expandedDrawX = expandedBounds.centerX() - (expandedTextWidth / 2);
break;
case Gravity.RIGHT:
expandedDrawX = expandedBounds.right - expandedTextWidth;
break;
case Gravity.LEFT:
default:
expandedDrawX = expandedBounds.left;
break;
}
// Now reset the text size back to the original
setInterpolatedTextSize(expandedFraction);
}
private float measureTextWidth(TextPaint textPaint, CharSequence textToDraw) {
return textPaint.measureText(textToDraw, 0, textToDraw.length());
}
private void interpolateBounds(float fraction) {
if (fadeModeEnabled) {
currentBounds.set(fraction < fadeModeThresholdFraction ? expandedBounds : collapsedBounds);
} else {
currentBounds.left =
lerp(expandedBounds.left, collapsedBounds.left, fraction, positionInterpolator);
currentBounds.top = lerp(expandedDrawY, collapsedDrawY, fraction, positionInterpolator);
currentBounds.right =
lerp(expandedBounds.right, collapsedBounds.right, fraction, positionInterpolator);
currentBounds.bottom =
lerp(expandedBounds.bottom, collapsedBounds.bottom, fraction, positionInterpolator);
}
}
private void setCollapsedTextBlend(float blend) {
collapsedTextBlend = blend;
view.postInvalidateOnAnimation();
}
private void setExpandedTextBlend(float blend) {
expandedTextBlend = blend;
view.postInvalidateOnAnimation();
}
public void draw(@NonNull Canvas canvas) {
final int saveCount = canvas.save();
// Compute where to draw textLayout for this frame
if (textToDraw != null && currentBounds.width() > 0 && currentBounds.height() > 0) {
textPaint.setTextSize(currentTextSize);
float x = currentDrawX;
float y = currentDrawY;
if (DEBUG_DRAW) {
// Just a debug tool, which draws semitransparent magenta rects in the expanded bounds and
// text bounds.
canvas.drawRect(expandedBounds, DEBUG_DRAW_PAINT);
canvas.drawRect(
x,
y,
x + textLayout.getWidth() * scale,
y + textLayout.getHeight() * scale,
DEBUG_DRAW_PAINT);
}
if (scale != 1f && !fadeModeEnabled) {
canvas.scale(scale, scale, x, y);
}
if (shouldDrawMultiline()
&& shouldTruncateCollapsedToSingleLine()
&& (!fadeModeEnabled || expandedFraction > fadeModeThresholdFraction)) {
drawMultilineTransition(canvas, currentDrawX - textLayout.getLineStart(0), y);
} else {
canvas.translate(x, y);
textLayout.draw(canvas);
}
canvas.restoreToCount(saveCount);
}
}
private boolean shouldDrawMultiline() {
return (expandedMaxLines > 1 || collapsedMaxLines > 1) && (!isRtl || fadeModeEnabled);
}
private void drawMultilineTransition(@NonNull Canvas canvas, float currentExpandedX, float y) {
int originalAlpha = textPaint.getAlpha();
// position text appropriately
canvas.translate(currentExpandedX, y);
if (!fadeModeEnabled) {
// Expanded text (when not in fade mode, because in fade mode at this point the expanded text
// has been fully faded out, so there's no need to try to draw it again)
textPaint.setAlpha((int) (expandedTextBlend * originalAlpha));
// Workaround for API 31(+). Paint applies an inverse alpha of Paint object on the shadow
// layer when collapsing mode is scale and shadow color is opaque. The workaround is to set
// the shadow not opaque. Then Paint will respect to the color's alpha. Applying the shadow
// color for expanded text.
if (VERSION.SDK_INT >= VERSION_CODES.S) {
textPaint.setShadowLayer(
currentShadowRadius,
currentShadowDx,
currentShadowDy,
MaterialColors.compositeARGBWithAlpha(currentShadowColor, textPaint.getAlpha()));
}
textLayout.draw(canvas);
}
// Collapsed text
if (!fadeModeEnabled) {
// Only change the collapsed text alpha when not in fade mode, because when in fade mode it
// will be precalculated based on the current fraction in calculateOffsets()
textPaint.setAlpha((int) (collapsedTextBlend * originalAlpha));
}
// Workaround for API 31(+). Applying the shadow color for collapsed text.
if (VERSION.SDK_INT >= VERSION_CODES.S) {
textPaint.setShadowLayer(
currentShadowRadius,
currentShadowDx,
currentShadowDy,
MaterialColors.compositeARGBWithAlpha(currentShadowColor, textPaint.getAlpha()));
}
int lineBaseline = textLayout.getLineBaseline(0);
canvas.drawText(
textToDrawCollapsed,
/* start= */ 0,
textToDrawCollapsed.length(),
/* x= */ 0,
lineBaseline,
textPaint);
// Reverse workaround for API 31(+). Applying opaque shadow color after the expanded text and
// the collapsed text are drawn.
if (VERSION.SDK_INT >= VERSION_CODES.S) {
textPaint.setShadowLayer(
currentShadowRadius, currentShadowDx, currentShadowDy, currentShadowColor);
}
if (!fadeModeEnabled) {
// Remove ellipsis for Cross-section animation
String tmp = textToDrawCollapsed.toString().trim();
if (tmp.endsWith(ELLIPSIS_NORMAL)) {
tmp = tmp.substring(0, tmp.length() - 1);
}
// Cross-section between both texts (should stay at original alpha)
textPaint.setAlpha(originalAlpha);
canvas.drawText(
tmp,
/* start= */ 0,
min(textLayout.getLineEnd(0), tmp.length()),
/* x= */ 0,
lineBaseline,