/
CollapsingToolbarLayout.java
1814 lines (1595 loc) · 63.3 KB
/
CollapsingToolbarLayout.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.appbar;
import com.google.android.material.R;
import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP;
import static com.google.android.material.theme.overlay.MaterialThemeOverlay.wrap;
import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.Region.Op;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.FrameLayout;
import androidx.annotation.ColorInt;
import androidx.annotation.DrawableRes;
import androidx.annotation.FloatRange;
import androidx.annotation.IntDef;
import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.annotation.RestrictTo;
import androidx.annotation.StyleRes;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.core.math.MathUtils;
import androidx.core.util.ObjectsCompat;
import androidx.core.view.GravityCompat;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import com.google.android.material.animation.AnimationUtils;
import com.google.android.material.elevation.ElevationOverlayProvider;
import com.google.android.material.internal.CollapsingTextHelper;
import com.google.android.material.internal.DescendantOffsetUtils;
import com.google.android.material.internal.ThemeEnforcement;
import com.google.android.material.motion.MotionUtils;
import com.google.android.material.resources.MaterialResources;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* CollapsingToolbarLayout is a wrapper for {@code Toolbar} which implements a collapsing app bar.
* It is designed to be used as a direct child of a {@link AppBarLayout}. CollapsingToolbarLayout
* contains the following features:
*
* <h4>Collapsing title</h4>
*
* A title which is larger when the layout is fully visible but collapses and becomes smaller as the
* layout is scrolled off screen. You can set the title to display via {@link
* #setTitle(CharSequence)}. The title appearance can be tweaked via the {@code
* collapsedTextAppearance} and {@code expandedTextAppearance} attributes.
*
* <h4>Content scrim</h4>
*
* A full-bleed scrim which is show or hidden when the scroll position has hit a certain threshold.
* You can change this via {@link #setContentScrim(Drawable)}.
*
* <h4>Status bar scrim</h4>
*
* A scrim which is shown or hidden behind the status bar when the scroll position has hit a certain
* threshold. You can change this via {@link #setStatusBarScrim(Drawable)}. This only works on
* {@link android.os.Build.VERSION_CODES#LOLLIPOP LOLLIPOP} devices when we set to fit system
* windows.
*
* <h4>Parallax scrolling children</h4>
*
* Child views can opt to be scrolled within this layout in a parallax fashion. See {@link
* LayoutParams#COLLAPSE_MODE_PARALLAX} and {@link LayoutParams#setParallaxMultiplier(float)}.
*
* <h4>Pinned position children</h4>
*
* Child views can opt to be pinned in space globally. This is useful when implementing a collapsing
* as it allows the {@code Toolbar} to be fixed in place even though this layout is moving. See
* {@link LayoutParams#COLLAPSE_MODE_PIN}.
*
* <p><strong>Do not manually add views to the Toolbar at run time</strong>. We will add a 'dummy
* view' to the Toolbar which allows us to work out the available space for the title. This can
* interfere with any views which you add.
*
* <p>For more information, see the <a
* href="https://github.com/material-components/material-components-android/blob/master/docs/components/TopAppBar.md">component
* developer guidance</a> and <a href="https://material.io/components/top-app-bar/overview">design
* guidelines</a>.
*
* @attr ref
* com.google.android.material.R.styleable#CollapsingToolbarLayout_collapsedTitleTextAppearance
* @attr ref
* com.google.android.material.R.styleable#CollapsingToolbarLayout_expandedTitleTextAppearance
* @attr ref com.google.android.material.R.styleable#CollapsingToolbarLayout_contentScrim
* @attr ref com.google.android.material.R.styleable#CollapsingToolbarLayout_expandedTitleMargin
* @attr ref
* com.google.android.material.R.styleable#CollapsingToolbarLayout_expandedTitleMarginStart
* @attr ref com.google.android.material.R.styleable#CollapsingToolbarLayout_expandedTitleMarginEnd
* @attr ref
* com.google.android.material.R.styleable#CollapsingToolbarLayout_expandedTitleMarginBottom
* @attr ref com.google.android.material.R.styleable#CollapsingToolbarLayout_statusBarScrim
* @attr ref com.google.android.material.R.styleable#CollapsingToolbarLayout_toolbarId
*/
public class CollapsingToolbarLayout extends FrameLayout {
private static final int DEF_STYLE_RES = R.style.Widget_Design_CollapsingToolbar;
private static final int DEFAULT_SCRIM_ANIMATION_DURATION = 600;
/**
* The expanded title will continuously scale and translate to its final collapsed position.
*
* @see #setTitleCollapseMode(int)
* @see #getTitleCollapseMode()
*/
public static final int TITLE_COLLAPSE_MODE_SCALE = 0;
/**
* The expanded title will fade out and translate, and the collapsed title will fade in.
*
* @see #setTitleCollapseMode(int)
* @see #getTitleCollapseMode()
*/
public static final int TITLE_COLLAPSE_MODE_FADE = 1;
/** @hide */
@RestrictTo(LIBRARY_GROUP)
@IntDef(value = {TITLE_COLLAPSE_MODE_SCALE, TITLE_COLLAPSE_MODE_FADE})
@Retention(RetentionPolicy.SOURCE)
public @interface TitleCollapseMode {}
private boolean refreshToolbar = true;
private int toolbarId;
@Nullable private ViewGroup toolbar;
@Nullable private View toolbarDirectChild;
private View dummyView;
private int expandedMarginStart;
private int expandedMarginTop;
private int expandedMarginEnd;
private int expandedMarginBottom;
private final Rect tmpRect = new Rect();
@NonNull final CollapsingTextHelper collapsingTextHelper;
@NonNull final ElevationOverlayProvider elevationOverlayProvider;
private boolean collapsingTitleEnabled;
private boolean drawCollapsingTitle;
@Nullable private Drawable contentScrim;
@Nullable Drawable statusBarScrim;
private int scrimAlpha;
private boolean scrimsAreShown;
private ValueAnimator scrimAnimator;
private long scrimAnimationDuration;
private final TimeInterpolator scrimAnimationFadeInInterpolator;
private final TimeInterpolator scrimAnimationFadeOutInterpolator;
private int scrimVisibleHeightTrigger = -1;
private AppBarLayout.OnOffsetChangedListener onOffsetChangedListener;
int currentOffset;
@TitleCollapseMode private int titleCollapseMode;
@Nullable WindowInsetsCompat lastInsets;
private int topInsetApplied = 0;
private boolean forceApplySystemWindowInsetTop;
private int extraMultilineHeight = 0;
private boolean extraMultilineHeightEnabled;
public CollapsingToolbarLayout(@NonNull Context context) {
this(context, null);
}
public CollapsingToolbarLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, R.attr.collapsingToolbarLayoutStyle);
}
public CollapsingToolbarLayout(@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();
collapsingTextHelper = new CollapsingTextHelper(this);
collapsingTextHelper.setTextSizeInterpolator(AnimationUtils.DECELERATE_INTERPOLATOR);
collapsingTextHelper.setRtlTextDirectionHeuristicsEnabled(false);
elevationOverlayProvider = new ElevationOverlayProvider(context);
TypedArray a =
ThemeEnforcement.obtainStyledAttributes(
context,
attrs,
R.styleable.CollapsingToolbarLayout,
defStyleAttr,
DEF_STYLE_RES);
collapsingTextHelper.setExpandedTextGravity(
a.getInt(
R.styleable.CollapsingToolbarLayout_expandedTitleGravity,
GravityCompat.START | Gravity.BOTTOM));
collapsingTextHelper.setCollapsedTextGravity(
a.getInt(
R.styleable.CollapsingToolbarLayout_collapsedTitleGravity,
GravityCompat.START | Gravity.CENTER_VERTICAL));
expandedMarginStart =
expandedMarginTop =
expandedMarginEnd =
expandedMarginBottom =
a.getDimensionPixelSize(
R.styleable.CollapsingToolbarLayout_expandedTitleMargin, 0);
if (a.hasValue(R.styleable.CollapsingToolbarLayout_expandedTitleMarginStart)) {
expandedMarginStart =
a.getDimensionPixelSize(R.styleable.CollapsingToolbarLayout_expandedTitleMarginStart, 0);
}
if (a.hasValue(R.styleable.CollapsingToolbarLayout_expandedTitleMarginEnd)) {
expandedMarginEnd =
a.getDimensionPixelSize(R.styleable.CollapsingToolbarLayout_expandedTitleMarginEnd, 0);
}
if (a.hasValue(R.styleable.CollapsingToolbarLayout_expandedTitleMarginTop)) {
expandedMarginTop =
a.getDimensionPixelSize(R.styleable.CollapsingToolbarLayout_expandedTitleMarginTop, 0);
}
if (a.hasValue(R.styleable.CollapsingToolbarLayout_expandedTitleMarginBottom)) {
expandedMarginBottom =
a.getDimensionPixelSize(R.styleable.CollapsingToolbarLayout_expandedTitleMarginBottom, 0);
}
collapsingTitleEnabled = a.getBoolean(R.styleable.CollapsingToolbarLayout_titleEnabled, true);
setTitle(a.getText(R.styleable.CollapsingToolbarLayout_title));
// First load the default text appearances
collapsingTextHelper.setExpandedTextAppearance(
R.style.TextAppearance_Design_CollapsingToolbar_Expanded);
collapsingTextHelper.setCollapsedTextAppearance(
androidx.appcompat.R.style.TextAppearance_AppCompat_Widget_ActionBar_Title);
// Now overlay any custom text appearances
if (a.hasValue(R.styleable.CollapsingToolbarLayout_expandedTitleTextAppearance)) {
collapsingTextHelper.setExpandedTextAppearance(
a.getResourceId(R.styleable.CollapsingToolbarLayout_expandedTitleTextAppearance, 0));
}
if (a.hasValue(R.styleable.CollapsingToolbarLayout_collapsedTitleTextAppearance)) {
collapsingTextHelper.setCollapsedTextAppearance(
a.getResourceId(R.styleable.CollapsingToolbarLayout_collapsedTitleTextAppearance, 0));
}
// Now overlay any custom text Ellipsize
if (a.hasValue(R.styleable.CollapsingToolbarLayout_titleTextEllipsize)) {
setTitleEllipsize(
convertEllipsizeToTruncateAt(
a.getInt(R.styleable.CollapsingToolbarLayout_titleTextEllipsize, -1)));
}
if (a.hasValue(R.styleable.CollapsingToolbarLayout_expandedTitleTextColor)) {
collapsingTextHelper.setExpandedTextColor(
MaterialResources.getColorStateList(
context, a, R.styleable.CollapsingToolbarLayout_expandedTitleTextColor));
}
if (a.hasValue(R.styleable.CollapsingToolbarLayout_collapsedTitleTextColor)) {
collapsingTextHelper.setCollapsedTextColor(
MaterialResources.getColorStateList(
context, a, R.styleable.CollapsingToolbarLayout_collapsedTitleTextColor));
}
scrimVisibleHeightTrigger =
a.getDimensionPixelSize(R.styleable.CollapsingToolbarLayout_scrimVisibleHeightTrigger, -1);
if (a.hasValue(R.styleable.CollapsingToolbarLayout_maxLines)) {
collapsingTextHelper.setMaxLines(a.getInt(R.styleable.CollapsingToolbarLayout_maxLines, 1));
}
if (a.hasValue(R.styleable.CollapsingToolbarLayout_titlePositionInterpolator)) {
collapsingTextHelper.setPositionInterpolator(
android.view.animation.AnimationUtils.loadInterpolator(
context,
a.getResourceId(R.styleable.CollapsingToolbarLayout_titlePositionInterpolator, 0)));
}
scrimAnimationDuration =
a.getInt(
R.styleable.CollapsingToolbarLayout_scrimAnimationDuration,
DEFAULT_SCRIM_ANIMATION_DURATION);
scrimAnimationFadeInInterpolator =
MotionUtils.resolveThemeInterpolator(
context,
R.attr.motionEasingStandardInterpolator,
AnimationUtils.FAST_OUT_LINEAR_IN_INTERPOLATOR);
scrimAnimationFadeOutInterpolator =
MotionUtils.resolveThemeInterpolator(
context,
R.attr.motionEasingStandardInterpolator,
AnimationUtils.LINEAR_OUT_SLOW_IN_INTERPOLATOR);
setContentScrim(a.getDrawable(R.styleable.CollapsingToolbarLayout_contentScrim));
setStatusBarScrim(a.getDrawable(R.styleable.CollapsingToolbarLayout_statusBarScrim));
setTitleCollapseMode(
a.getInt(R.styleable.CollapsingToolbarLayout_titleCollapseMode, TITLE_COLLAPSE_MODE_SCALE));
toolbarId = a.getResourceId(R.styleable.CollapsingToolbarLayout_toolbarId, -1);
forceApplySystemWindowInsetTop =
a.getBoolean(R.styleable.CollapsingToolbarLayout_forceApplySystemWindowInsetTop, false);
extraMultilineHeightEnabled =
a.getBoolean(R.styleable.CollapsingToolbarLayout_extraMultilineHeightEnabled, false);
a.recycle();
setWillNotDraw(false);
ViewCompat.setOnApplyWindowInsetsListener(
this,
new androidx.core.view.OnApplyWindowInsetsListener() {
@Override
public WindowInsetsCompat onApplyWindowInsets(
View v, @NonNull WindowInsetsCompat insets) {
return onWindowInsetChanged(insets);
}
});
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
// Add an OnOffsetChangedListener if possible
final ViewParent parent = getParent();
if (parent instanceof AppBarLayout) {
AppBarLayout appBarLayout = (AppBarLayout) parent;
disableLiftOnScrollIfNeeded(appBarLayout);
// Copy over from the ABL whether we should fit system windows
ViewCompat.setFitsSystemWindows(this, ViewCompat.getFitsSystemWindows(appBarLayout));
if (onOffsetChangedListener == null) {
onOffsetChangedListener = new OffsetUpdateListener();
}
appBarLayout.addOnOffsetChangedListener(onOffsetChangedListener);
// We're attached, so lets request an inset dispatch
ViewCompat.requestApplyInsets(this);
}
}
@Override
protected void onDetachedFromWindow() {
// Remove our OnOffsetChangedListener if possible and it exists
final ViewParent parent = getParent();
if (onOffsetChangedListener != null && parent instanceof AppBarLayout) {
((AppBarLayout) parent).removeOnOffsetChangedListener(onOffsetChangedListener);
}
super.onDetachedFromWindow();
}
WindowInsetsCompat onWindowInsetChanged(@NonNull final WindowInsetsCompat insets) {
WindowInsetsCompat newInsets = null;
if (ViewCompat.getFitsSystemWindows(this)) {
// If we're set to fit system windows, keep the insets
newInsets = insets;
}
// If our insets have changed, keep them and invalidate the scroll ranges...
if (!ObjectsCompat.equals(lastInsets, newInsets)) {
lastInsets = newInsets;
requestLayout();
}
// Consume the insets. This is done so that child views with fitSystemWindows=true do not
// get the default padding functionality from View
return insets.consumeSystemWindowInsets();
}
@Override
public void draw(@NonNull Canvas canvas) {
super.draw(canvas);
// If we don't have a toolbar, the scrim will be not be drawn in drawChild() below.
// Instead, we draw it here, before our collapsing text.
ensureToolbar();
if (toolbar == null && contentScrim != null && scrimAlpha > 0) {
contentScrim.mutate().setAlpha(scrimAlpha);
contentScrim.draw(canvas);
}
// Let the collapsing text helper draw its text
if (collapsingTitleEnabled && drawCollapsingTitle) {
if (toolbar != null
&& contentScrim != null
&& scrimAlpha > 0
&& isTitleCollapseFadeMode()
&& collapsingTextHelper.getExpansionFraction()
< collapsingTextHelper.getFadeModeThresholdFraction()) {
// Mask the expanded text with the contentScrim
int save = canvas.save();
canvas.clipRect(contentScrim.getBounds(), Op.DIFFERENCE);
collapsingTextHelper.draw(canvas);
canvas.restoreToCount(save);
} else {
collapsingTextHelper.draw(canvas);
}
}
// Now draw the status bar scrim
if (statusBarScrim != null && scrimAlpha > 0) {
final int topInset = lastInsets != null ? lastInsets.getSystemWindowInsetTop() : 0;
if (topInset > 0) {
statusBarScrim.setBounds(0, -currentOffset, getWidth(), topInset - currentOffset);
statusBarScrim.mutate().setAlpha(scrimAlpha);
statusBarScrim.draw(canvas);
}
}
}
@Override
protected void onConfigurationChanged(@NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
collapsingTextHelper.maybeUpdateFontWeightAdjustment(newConfig);
}
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
// This is a little weird. Our scrim needs to be behind the Toolbar (if it is present),
// but in front of any other children which are behind it. To do this we intercept the
// drawChild() call, and draw our scrim just before the Toolbar is drawn
boolean invalidated = false;
if (contentScrim != null && scrimAlpha > 0 && isToolbarChild(child)) {
updateContentScrimBounds(contentScrim, child, getWidth(), getHeight());
contentScrim.mutate().setAlpha(scrimAlpha);
contentScrim.draw(canvas);
invalidated = true;
}
return super.drawChild(canvas, child, drawingTime) || invalidated;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (contentScrim != null) {
updateContentScrimBounds(contentScrim, w, h);
}
}
private boolean isTitleCollapseFadeMode() {
return titleCollapseMode == TITLE_COLLAPSE_MODE_FADE;
}
private void disableLiftOnScrollIfNeeded(AppBarLayout appBarLayout) {
// Disable lift on scroll if using fade title collapse mode, since the content scrim can
// conflict with the lift on scroll color fill.
if (isTitleCollapseFadeMode()) {
appBarLayout.setLiftOnScroll(false);
}
}
private void updateContentScrimBounds(@NonNull Drawable contentScrim, int width, int height) {
updateContentScrimBounds(contentScrim, this.toolbar, width, height);
}
private void updateContentScrimBounds(
@NonNull Drawable contentScrim, @Nullable View toolbar, int width, int height) {
// If using fade title collapse mode and we have a toolbar with a collapsing title, use the
// toolbar's bottom edge for the scrim so the collapsing title appears to go under the toolbar.
int bottom =
isTitleCollapseFadeMode() && toolbar != null && collapsingTitleEnabled
? toolbar.getBottom()
: height;
contentScrim.setBounds(0, 0, width, bottom);
}
private void ensureToolbar() {
if (!refreshToolbar) {
return;
}
// First clear out the current Toolbar
this.toolbar = null;
toolbarDirectChild = null;
if (toolbarId != -1) {
// If we have an ID set, try and find it and it's direct parent to us
this.toolbar = findViewById(toolbarId);
if (this.toolbar != null) {
toolbarDirectChild = findDirectChild(this.toolbar);
}
}
if (this.toolbar == null) {
// If we don't have an ID, or couldn't find a Toolbar with the correct ID, try and find
// one from our direct children
ViewGroup toolbar = null;
for (int i = 0, count = getChildCount(); i < count; i++) {
final View child = getChildAt(i);
if (isToolbar(child)) {
toolbar = (ViewGroup) child;
break;
}
}
this.toolbar = toolbar;
}
updateDummyView();
refreshToolbar = false;
}
private static boolean isToolbar(View view) {
return view instanceof androidx.appcompat.widget.Toolbar
|| (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP && view instanceof android.widget.Toolbar);
}
private boolean isToolbarChild(View child) {
return (toolbarDirectChild == null || toolbarDirectChild == this)
? child == toolbar
: child == toolbarDirectChild;
}
/** Returns the direct child of this layout, which itself is the ancestor of the given view. */
@NonNull
private View findDirectChild(@NonNull final View descendant) {
View directChild = descendant;
for (ViewParent p = descendant.getParent(); p != this && p != null; p = p.getParent()) {
if (p instanceof View) {
directChild = (View) p;
}
}
return directChild;
}
private void updateDummyView() {
if (!collapsingTitleEnabled && dummyView != null) {
// If we have a dummy view and we have our title disabled, remove it from its parent
final ViewParent parent = dummyView.getParent();
if (parent instanceof ViewGroup) {
((ViewGroup) parent).removeView(dummyView);
}
}
if (collapsingTitleEnabled && toolbar != null) {
if (dummyView == null) {
dummyView = new View(getContext());
}
if (dummyView.getParent() == null) {
toolbar.addView(dummyView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
}
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
ensureToolbar();
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final int mode = MeasureSpec.getMode(heightMeasureSpec);
final int topInset = lastInsets != null ? lastInsets.getSystemWindowInsetTop() : 0;
if ((mode == MeasureSpec.UNSPECIFIED || forceApplySystemWindowInsetTop) && topInset > 0) {
// If we have a top inset and we're set to wrap_content height or force apply,
// we need to make sure we add the top inset to our height, therefore we re-measure
topInsetApplied = topInset;
int newHeight = getMeasuredHeight() + topInset;
heightMeasureSpec = MeasureSpec.makeMeasureSpec(newHeight, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
if (extraMultilineHeightEnabled && collapsingTextHelper.getMaxLines() > 1) {
// Need to update title and bounds in order to calculate line count and text height.
updateTitleFromToolbarIfNeeded();
updateTextBounds(0, 0, getMeasuredWidth(), getMeasuredHeight(), /* forceRecalculate= */ true);
int lineCount = collapsingTextHelper.getExpandedLineCount();
if (lineCount > 1) {
// Add extra height based on the amount of height beyond the first line of title text.
int expandedTextHeight = Math.round(collapsingTextHelper.getExpandedTextFullHeight());
extraMultilineHeight = expandedTextHeight * (lineCount - 1);
int newHeight = getMeasuredHeight() + extraMultilineHeight;
heightMeasureSpec = MeasureSpec.makeMeasureSpec(newHeight, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
// Set our minimum height to enable proper AppBarLayout collapsing
if (toolbar != null) {
if (toolbarDirectChild == null || toolbarDirectChild == this) {
setMinimumHeight(getHeightWithMargins(toolbar));
} else {
setMinimumHeight(getHeightWithMargins(toolbarDirectChild));
}
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (lastInsets != null) {
// Shift down any views which are not set to fit system windows
final int insetTop = lastInsets.getSystemWindowInsetTop();
for (int i = 0, z = getChildCount(); i < z; i++) {
final View child = getChildAt(i);
if (!ViewCompat.getFitsSystemWindows(child)) {
if (child.getTop() < insetTop) {
// If the child isn't set to fit system windows but is drawing within
// the inset offset it down
ViewCompat.offsetTopAndBottom(child, insetTop);
}
}
}
}
// Update our child view offset helpers so that they track the correct layout coordinates
for (int i = 0, z = getChildCount(); i < z; i++) {
getViewOffsetHelper(getChildAt(i)).onViewLayout();
}
updateTextBounds(left, top, right, bottom, /* forceRecalculate= */false);
updateTitleFromToolbarIfNeeded();
updateScrimVisibility();
// Apply any view offsets, this should be done at the very end of layout
for (int i = 0, z = getChildCount(); i < z; i++) {
getViewOffsetHelper(getChildAt(i)).applyOffsets();
}
}
private void updateTextBounds(
int left, int top, int right, int bottom, boolean forceRecalculate) {
// Update the collapsed bounds by getting its transformed bounds
if (collapsingTitleEnabled && dummyView != null) {
// We only draw the title if the dummy view is being displayed (Toolbar removes
// views if there is no space)
drawCollapsingTitle =
ViewCompat.isAttachedToWindow(dummyView) && dummyView.getVisibility() == VISIBLE;
if (drawCollapsingTitle || forceRecalculate) {
final boolean isRtl =
ViewCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_RTL;
// Update the collapsed bounds
updateCollapsedBounds(isRtl);
// Update the expanded bounds
collapsingTextHelper.setExpandedBounds(
isRtl ? expandedMarginEnd : expandedMarginStart,
tmpRect.top + expandedMarginTop,
right - left - (isRtl ? expandedMarginStart : expandedMarginEnd),
bottom - top - expandedMarginBottom);
// Now recalculate using the new bounds
collapsingTextHelper.recalculate(forceRecalculate);
}
}
}
private void updateTitleFromToolbarIfNeeded() {
if (toolbar != null) {
if (collapsingTitleEnabled && TextUtils.isEmpty(collapsingTextHelper.getText())) {
// If we do not currently have a title, try and grab it from the Toolbar
setTitle(getToolbarTitle(toolbar));
}
}
}
private void updateCollapsedBounds(boolean isRtl) {
final int maxOffset =
getMaxOffsetForPinChild(toolbarDirectChild != null ? toolbarDirectChild : toolbar);
DescendantOffsetUtils.getDescendantRect(this, dummyView, tmpRect);
final int titleMarginStart;
final int titleMarginEnd;
final int titleMarginTop;
final int titleMarginBottom;
if (toolbar instanceof androidx.appcompat.widget.Toolbar) {
androidx.appcompat.widget.Toolbar compatToolbar = (androidx.appcompat.widget.Toolbar) toolbar;
titleMarginStart = compatToolbar.getTitleMarginStart();
titleMarginEnd = compatToolbar.getTitleMarginEnd();
titleMarginTop = compatToolbar.getTitleMarginTop();
titleMarginBottom = compatToolbar.getTitleMarginBottom();
} else if (VERSION.SDK_INT >= VERSION_CODES.N && toolbar instanceof android.widget.Toolbar) {
android.widget.Toolbar frameworkToolbar = (android.widget.Toolbar) toolbar;
titleMarginStart = frameworkToolbar.getTitleMarginStart();
titleMarginEnd = frameworkToolbar.getTitleMarginEnd();
titleMarginTop = frameworkToolbar.getTitleMarginTop();
titleMarginBottom = frameworkToolbar.getTitleMarginBottom();
} else {
titleMarginStart = 0;
titleMarginEnd = 0;
titleMarginTop = 0;
titleMarginBottom = 0;
}
collapsingTextHelper.setCollapsedBounds(
tmpRect.left + (isRtl ? titleMarginEnd : titleMarginStart),
tmpRect.top + maxOffset + titleMarginTop,
tmpRect.right - (isRtl ? titleMarginStart : titleMarginEnd),
tmpRect.bottom + maxOffset - titleMarginBottom);
}
private static CharSequence getToolbarTitle(View view) {
if (view instanceof androidx.appcompat.widget.Toolbar) {
return ((androidx.appcompat.widget.Toolbar) view).getTitle();
} else if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP
&& view instanceof android.widget.Toolbar) {
return ((android.widget.Toolbar) view).getTitle();
} else {
return null;
}
}
private static int getHeightWithMargins(@NonNull final View view) {
final ViewGroup.LayoutParams lp = view.getLayoutParams();
if (lp instanceof MarginLayoutParams) {
final MarginLayoutParams mlp = (MarginLayoutParams) lp;
return view.getMeasuredHeight() + mlp.topMargin + mlp.bottomMargin;
}
return view.getMeasuredHeight();
}
@NonNull
static ViewOffsetHelper getViewOffsetHelper(@NonNull View view) {
ViewOffsetHelper offsetHelper = (ViewOffsetHelper) view.getTag(R.id.view_offset_helper);
if (offsetHelper == null) {
offsetHelper = new ViewOffsetHelper(view);
view.setTag(R.id.view_offset_helper, offsetHelper);
}
return offsetHelper;
}
/**
* Sets the title to be displayed by this view, if enabled.
*
* @see #setTitleEnabled(boolean)
* @see #getTitle()
* @attr ref R.styleable#CollapsingToolbarLayout_title
*/
public void setTitle(@Nullable CharSequence title) {
collapsingTextHelper.setText(title);
updateContentDescriptionFromTitle();
}
/**
* Returns the title currently being displayed by this view. If the title is not enabled, then
* this will return {@code null}.
*
* @attr ref R.styleable#CollapsingToolbarLayout_title
*/
@Nullable
public CharSequence getTitle() {
return collapsingTitleEnabled ? collapsingTextHelper.getText() : null;
}
/**
* Sets the title collapse mode which determines the effect used to collapse and expand the title
* text.
*
* @attr ref R.styleable#CollapsingToolbarLayout_titleCollapseMode
*/
public void setTitleCollapseMode(@TitleCollapseMode int titleCollapseMode) {
this.titleCollapseMode = titleCollapseMode;
boolean fadeModeEnabled = isTitleCollapseFadeMode();
collapsingTextHelper.setFadeModeEnabled(fadeModeEnabled);
ViewParent parent = getParent();
if (parent instanceof AppBarLayout) {
disableLiftOnScrollIfNeeded((AppBarLayout) parent);
}
// If using fade title collapse mode and no content scrim, provide default content scrim based
// on elevation overlay.
if (fadeModeEnabled && contentScrim == null) {
float appBarElevation = getResources().getDimension(R.dimen.design_appbar_elevation);
int scrimColor =
elevationOverlayProvider.compositeOverlayWithThemeSurfaceColorIfNeeded(appBarElevation);
setContentScrimColor(scrimColor);
}
}
/**
* Returns the current title collapse mode.
*
* @attr ref R.styleable#CollapsingToolbarLayout_titleCollapseMode
*/
@TitleCollapseMode
public int getTitleCollapseMode() {
return titleCollapseMode;
}
/**
* Sets whether this view should display its own title.
*
* <p>The title displayed by this view will shrink and grow based on the scroll offset.
*
* @see #setTitle(CharSequence)
* @see #isTitleEnabled()
* @attr ref R.styleable#CollapsingToolbarLayout_titleEnabled
*/
public void setTitleEnabled(boolean enabled) {
if (enabled != collapsingTitleEnabled) {
collapsingTitleEnabled = enabled;
updateContentDescriptionFromTitle();
updateDummyView();
requestLayout();
}
}
/**
* Returns whether this view is currently displaying its own title.
*
* @see #setTitleEnabled(boolean)
* @attr ref R.styleable#CollapsingToolbarLayout_titleEnabled
*/
public boolean isTitleEnabled() {
return collapsingTitleEnabled;
}
/**
* Set ellipsizing on the title text.
*
* @param ellipsize type of ellipsis behavior
* @attr ref R.styleable#CollapsingToolbarLayout_titleTextEllipsize
*/
public void setTitleEllipsize(@NonNull TruncateAt ellipsize) {
collapsingTextHelper.setTitleTextEllipsize(ellipsize);
}
/**
* Get ellipsizing currently applied on the title text.
*/
@NonNull
public TruncateAt getTitleTextEllipsize() {
return collapsingTextHelper.getTitleTextEllipsize();
}
// Convert to supported TruncateAt values
private TruncateAt convertEllipsizeToTruncateAt(int ellipsize) {
switch (ellipsize) {
case 0:
return TruncateAt.START;
case 1:
return TruncateAt.MIDDLE;
case 3:
return TruncateAt.MARQUEE;
case 2:
default:
return TruncateAt.END;
}
}
/**
* Set whether the content scrim and/or status bar scrim should be shown or not. Any change in the
* vertical scroll may overwrite this value. Any visibility change will be animated if this view
* has already been laid out.
*
* @param shown whether the scrims should be shown
* @see #getStatusBarScrim()
* @see #getContentScrim()
*/
public void setScrimsShown(boolean shown) {
setScrimsShown(shown, ViewCompat.isLaidOut(this) && !isInEditMode());
}
/**
* Set whether the content scrim and/or status bar scrim should be shown or not. Any change in the
* vertical scroll may overwrite this value.
*
* @param shown whether the scrims should be shown
* @param animate whether to animate the visibility change
* @see #getStatusBarScrim()
* @see #getContentScrim()
*/
public void setScrimsShown(boolean shown, boolean animate) {
if (scrimsAreShown != shown) {
if (animate) {
animateScrim(shown ? 0xFF : 0x0);
} else {
setScrimAlpha(shown ? 0xFF : 0x0);
}
scrimsAreShown = shown;
}
}
private void animateScrim(int targetAlpha) {
ensureToolbar();
if (scrimAnimator == null) {
scrimAnimator = new ValueAnimator();
scrimAnimator.setInterpolator(
targetAlpha > scrimAlpha
? scrimAnimationFadeInInterpolator
: scrimAnimationFadeOutInterpolator);
scrimAnimator.addUpdateListener(
new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(@NonNull ValueAnimator animator) {
setScrimAlpha((int) animator.getAnimatedValue());
}
});
} else if (scrimAnimator.isRunning()) {
scrimAnimator.cancel();
}
scrimAnimator.setDuration(scrimAnimationDuration);
scrimAnimator.setIntValues(scrimAlpha, targetAlpha);
scrimAnimator.start();
}
void setScrimAlpha(int alpha) {
if (alpha != scrimAlpha) {
final Drawable contentScrim = this.contentScrim;
if (contentScrim != null && toolbar != null) {
ViewCompat.postInvalidateOnAnimation(toolbar);
}
scrimAlpha = alpha;
ViewCompat.postInvalidateOnAnimation(CollapsingToolbarLayout.this);
}
}
int getScrimAlpha() {
return scrimAlpha;
}
/**
* Set the drawable to use for the content scrim from resources. Providing null will disable the
* scrim functionality.
*
* @param drawable the drawable to display
* @attr ref R.styleable#CollapsingToolbarLayout_contentScrim
* @see #getContentScrim()
*/
public void setContentScrim(@Nullable Drawable drawable) {
if (contentScrim != drawable) {
if (contentScrim != null) {
contentScrim.setCallback(null);
}
contentScrim = drawable != null ? drawable.mutate() : null;
if (contentScrim != null) {
updateContentScrimBounds(contentScrim, getWidth(), getHeight());
contentScrim.setCallback(this);
contentScrim.setAlpha(scrimAlpha);
}
ViewCompat.postInvalidateOnAnimation(this);
}
}
/**
* Set the color to use for the content scrim.
*
* @param color the color to display
* @attr ref R.styleable#CollapsingToolbarLayout_contentScrim
* @see #getContentScrim()
*/
public void setContentScrimColor(@ColorInt int color) {
setContentScrim(new ColorDrawable(color));
}
/**
* Set the drawable to use for the content scrim from resources.
*
* @param resId drawable resource id
* @attr ref R.styleable#CollapsingToolbarLayout_contentScrim
* @see #getContentScrim()
*/
public void setContentScrimResource(@DrawableRes int resId) {
setContentScrim(ContextCompat.getDrawable(getContext(), resId));
}
/**
* Returns the drawable which is used for the foreground scrim.
*