-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
AppBarLayout.java
2590 lines (2270 loc) · 96.6 KB
/
AppBarLayout.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 androidx.core.math.MathUtils.clamp;
import static androidx.core.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat.ACTION_SCROLL_BACKWARD;
import static androidx.core.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat.ACTION_SCROLL_FORWARD;
import static com.google.android.material.theme.overlay.MaterialThemeOverlay.wrap;
import static java.lang.Math.abs;
import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import androidx.appcompat.content.res.AppCompatResources;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.view.animation.Interpolator;
import android.widget.AbsListView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import androidx.annotation.ColorInt;
import androidx.annotation.Dimension;
import androidx.annotation.DrawableRes;
import androidx.annotation.IdRes;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RestrictTo;
import androidx.annotation.VisibleForTesting;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.core.util.ObjectsCompat;
import androidx.core.view.AccessibilityDelegateCompat;
import androidx.core.view.NestedScrollingChild;
import androidx.core.view.ViewCompat;
import androidx.core.view.ViewCompat.NestedScrollType;
import androidx.core.view.WindowInsetsCompat;
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat;
import androidx.customview.view.AbsSavedState;
import com.google.android.material.animation.AnimationUtils;
import com.google.android.material.appbar.AppBarLayout.BaseBehavior.SavedState;
import com.google.android.material.color.MaterialColors;
import com.google.android.material.drawable.DrawableUtils;
import com.google.android.material.internal.ThemeEnforcement;
import com.google.android.material.motion.MotionUtils;
import com.google.android.material.resources.MaterialResources;
import com.google.android.material.shape.MaterialShapeDrawable;
import com.google.android.material.shape.MaterialShapeUtils;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
/**
* AppBarLayout is a vertical {@link LinearLayout} which implements many of the features of material
* designs app bar concept, namely scrolling gestures.
*
* <p>Children should provide their desired scrolling behavior through {@link
* LayoutParams#setScrollFlags(int)} and the associated layout xml attribute: {@code
* app:layout_scrollFlags}.
*
* <p>This view depends heavily on being used as a direct child within a {@link CoordinatorLayout}.
* If you use AppBarLayout within a different {@link ViewGroup}, most of its functionality will not
* work.
*
* <p>AppBarLayout also requires a separate scrolling sibling in order to know when to scroll. The
* binding is done through the {@link ScrollingViewBehavior} behavior class, meaning that you should
* set your scrolling view's behavior to be an instance of {@link ScrollingViewBehavior}. A string
* resource containing the full class name is available.
*
* <pre>
* <androidx.coordinatorlayout.widget.CoordinatorLayout
* xmlns:android="http://schemas.android.com/apk/res/android"
* xmlns:app="http://schemas.android.com/apk/res-auto"
* android:layout_width="match_parent"
* android:layout_height="match_parent">
*
* <androidx.core.widget.NestedScrollView
* android:layout_width="match_parent"
* android:layout_height="match_parent"
* app:layout_behavior="@string/appbar_scrolling_view_behavior">
*
* <!-- Your scrolling content -->
*
* </androidx.core.widget.NestedScrollView>
*
* <com.google.android.material.appbar.AppBarLayout
* android:layout_height="wrap_content"
* android:layout_width="match_parent">
*
* <androidx.appcompat.widget.Toolbar
* ...
* app:layout_scrollFlags="scroll|enterAlways"/>
*
* <com.google.android.material.tabs.TabLayout
* ...
* app:layout_scrollFlags="scroll|enterAlways"/>
*
* </com.google.android.material.appbar.AppBarLayout>
*
* </androidx.coordinatorlayout.widget.CoordinatorLayout>
* </pre>
*
* <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>.
*/
public class AppBarLayout extends LinearLayout implements CoordinatorLayout.AttachedBehavior {
static final int PENDING_ACTION_NONE = 0x0;
static final int PENDING_ACTION_EXPANDED = 0x1;
static final int PENDING_ACTION_COLLAPSED = 1 << 1;
static final int PENDING_ACTION_ANIMATE_ENABLED = 1 << 2;
static final int PENDING_ACTION_FORCE = 1 << 3;
/**
* Interface definition for a callback to be invoked when an {@link AppBarLayout}'s vertical
* offset changes.
*/
// TODO(b/76413401): remove this base interface after the widget migration
public interface BaseOnOffsetChangedListener<T extends AppBarLayout> {
/**
* Called when the {@link AppBarLayout}'s layout offset has been changed. This allows child
* views to implement custom behavior based on the offset (for instance pinning a view at a
* certain y value).
*
* @param appBarLayout the {@link AppBarLayout} which offset has changed
* @param verticalOffset the vertical offset for the parent {@link AppBarLayout}, in px
*/
void onOffsetChanged(T appBarLayout, int verticalOffset);
}
/**
* Interface definition for a callback to be invoked when an {@link AppBarLayout}'s vertical
* offset changes.
*/
// TODO(b/76413401): update this interface after the widget migration
public interface OnOffsetChangedListener extends BaseOnOffsetChangedListener<AppBarLayout> {
@Override
void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset);
}
/**
* Definition for a callback to be invoked when the lift on scroll elevation and background color
* change.
*/
public interface LiftOnScrollListener {
void onUpdate(@Dimension float elevation, @ColorInt int backgroundColor);
}
private static final int DEF_STYLE_RES = R.style.Widget_Design_AppBarLayout;
private static final int INVALID_SCROLL_RANGE = -1;
private int currentOffset;
private int totalScrollRange = INVALID_SCROLL_RANGE;
private int downPreScrollRange = INVALID_SCROLL_RANGE;
private int downScrollRange = INVALID_SCROLL_RANGE;
private boolean haveChildWithInterpolator;
private int pendingAction = PENDING_ACTION_NONE;
@Nullable private WindowInsetsCompat lastInsets;
private List<BaseOnOffsetChangedListener> listeners;
private boolean liftableOverride;
private boolean liftable;
private boolean lifted;
private boolean liftOnScroll;
@IdRes private int liftOnScrollTargetViewId;
@Nullable private WeakReference<View> liftOnScrollTargetView;
private final boolean hasLiftOnScrollColor;
@Nullable private ValueAnimator liftOnScrollColorAnimator;
@Nullable private AnimatorUpdateListener liftOnScrollColorUpdateListener;
private final List<LiftOnScrollListener> liftOnScrollListeners = new ArrayList<>();
private final long liftOnScrollColorDuration;
private final TimeInterpolator liftOnScrollColorInterpolator;
private int[] tmpStatesArray;
@Nullable private Drawable statusBarForeground;
@Nullable private Integer statusBarForegroundOriginalColor;
private final float appBarElevation;
private Behavior behavior;
public AppBarLayout(@NonNull Context context) {
this(context, null);
}
public AppBarLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, R.attr.appBarLayoutStyle);
}
public AppBarLayout(@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();
setOrientation(VERTICAL);
// Use the bounds view outline provider so that we cast a shadow, even without a background.
if (getOutlineProvider() == ViewOutlineProvider.BACKGROUND) {
ViewUtilsLollipop.setBoundsViewOutlineProvider(this);
}
// Reset any state list animator from our default style.
ViewUtilsLollipop.setStateListAnimatorFromAttrs(this, attrs, defStyleAttr, DEF_STYLE_RES);
final TypedArray a =
ThemeEnforcement.obtainStyledAttributes(
context, attrs, R.styleable.AppBarLayout, defStyleAttr, DEF_STYLE_RES);
setBackground(a.getDrawable(R.styleable.AppBarLayout_android_background));
ColorStateList liftOnScrollColor =
MaterialResources.getColorStateList(context, a, R.styleable.AppBarLayout_liftOnScrollColor);
hasLiftOnScrollColor = liftOnScrollColor != null;
ColorStateList originalBackgroundColor = DrawableUtils.getColorStateListOrNull(getBackground());
if (originalBackgroundColor != null) {
MaterialShapeDrawable materialShapeDrawable = new MaterialShapeDrawable();
materialShapeDrawable.setFillColor(originalBackgroundColor);
// If there is a lift on scroll color specified, we do not initialize the elevation overlay
// and set the alpha to zero manually.
if (liftOnScrollColor != null) {
initializeLiftOnScrollWithColor(
materialShapeDrawable, originalBackgroundColor, liftOnScrollColor);
} else {
initializeLiftOnScrollWithElevation(context, materialShapeDrawable);
}
}
liftOnScrollColorDuration = MotionUtils.resolveThemeDuration(context,
R.attr.motionDurationMedium2,
getResources().getInteger(R.integer.app_bar_elevation_anim_duration));
liftOnScrollColorInterpolator = MotionUtils.resolveThemeInterpolator(context,
R.attr.motionEasingStandardInterpolator, AnimationUtils.LINEAR_INTERPOLATOR);
if (a.hasValue(R.styleable.AppBarLayout_expanded)) {
setExpanded(
a.getBoolean(R.styleable.AppBarLayout_expanded, false),
/* animate= */ false,
/* force= */ false);
}
if (a.hasValue(R.styleable.AppBarLayout_elevation)) {
ViewUtilsLollipop.setDefaultAppBarLayoutStateListAnimator(
this, a.getDimensionPixelSize(R.styleable.AppBarLayout_elevation, 0));
}
if (VERSION.SDK_INT >= VERSION_CODES.O) {
// In O+, we have these values set in the style. Since there is no defStyleAttr for
// AppBarLayout at the AppCompat level, check for these attributes here.
if (a.hasValue(R.styleable.AppBarLayout_android_keyboardNavigationCluster)) {
this.setKeyboardNavigationCluster(
a.getBoolean(R.styleable.AppBarLayout_android_keyboardNavigationCluster, false));
}
if (a.hasValue(R.styleable.AppBarLayout_android_touchscreenBlocksFocus)) {
this.setTouchscreenBlocksFocus(
a.getBoolean(R.styleable.AppBarLayout_android_touchscreenBlocksFocus, false));
}
}
// TODO(b/249786834): This should be a customizable attribute.
appBarElevation = getResources().getDimension(R.dimen.design_appbar_elevation);
liftOnScroll = a.getBoolean(R.styleable.AppBarLayout_liftOnScroll, false);
liftOnScrollTargetViewId =
a.getResourceId(R.styleable.AppBarLayout_liftOnScrollTargetViewId, View.NO_ID);
setStatusBarForeground(a.getDrawable(R.styleable.AppBarLayout_statusBarForeground));
a.recycle();
ViewCompat.setOnApplyWindowInsetsListener(
this,
new androidx.core.view.OnApplyWindowInsetsListener() {
@Override
public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
return onWindowInsetChanged(insets);
}
});
}
private void initializeLiftOnScrollWithColor(
MaterialShapeDrawable background,
@NonNull ColorStateList originalBackgroundColor,
@NonNull ColorStateList liftOnScrollColor) {
Integer colorSurface = MaterialColors.getColorOrNull(getContext(), R.attr.colorSurface);
liftOnScrollColorUpdateListener =
valueAnimator -> {
float liftProgress = (float) valueAnimator.getAnimatedValue();
int mixedColor =
MaterialColors.layer(
originalBackgroundColor.getDefaultColor(),
liftOnScrollColor.getDefaultColor(),
liftProgress);
background.setFillColor(ColorStateList.valueOf(mixedColor));
if (statusBarForeground != null
&& statusBarForegroundOriginalColor != null
&& statusBarForegroundOriginalColor.equals(colorSurface)) {
DrawableCompat.setTint(statusBarForeground, mixedColor);
}
if (!liftOnScrollListeners.isEmpty()) {
for (LiftOnScrollListener liftOnScrollListener : liftOnScrollListeners) {
if (background.getFillColor() != null) {
liftOnScrollListener.onUpdate(0, mixedColor);
}
}
}
};
setBackground(background);
}
private void initializeLiftOnScrollWithElevation(
Context context, MaterialShapeDrawable background) {
background.initializeElevationOverlay(context);
liftOnScrollColorUpdateListener = valueAnimator -> {
float elevation = (float) valueAnimator.getAnimatedValue();
background.setElevation(elevation);
if (statusBarForeground instanceof MaterialShapeDrawable) {
((MaterialShapeDrawable) statusBarForeground).setElevation(elevation);
}
for (LiftOnScrollListener liftOnScrollListener : liftOnScrollListeners) {
liftOnScrollListener.onUpdate(elevation, background.getResolvedTintColor());
}
};
setBackground(background);
}
/**
* Add a listener that will be called when the offset of this {@link AppBarLayout} changes.
*
* @param listener The listener that will be called when the offset changes.]
* @see #removeOnOffsetChangedListener(OnOffsetChangedListener)
*/
@SuppressWarnings("FunctionalInterfaceClash")
public void addOnOffsetChangedListener(@Nullable BaseOnOffsetChangedListener listener) {
if (listeners == null) {
listeners = new ArrayList<>();
}
if (listener != null && !listeners.contains(listener)) {
listeners.add(listener);
}
}
@SuppressWarnings("FunctionalInterfaceClash")
public void addOnOffsetChangedListener(OnOffsetChangedListener listener) {
addOnOffsetChangedListener((BaseOnOffsetChangedListener) listener);
}
/**
* Remove the previously added {@link OnOffsetChangedListener}.
*
* @param listener the listener to remove.
*/
// TODO(b/76413401): change back to removeOnOffsetChangedListener once the widget migration is
// finished since the shim class needs to implement this method.
@SuppressWarnings("FunctionalInterfaceClash")
public void removeOnOffsetChangedListener(@Nullable BaseOnOffsetChangedListener listener) {
if (listeners != null && listener != null) {
listeners.remove(listener);
}
}
@SuppressWarnings("FunctionalInterfaceClash")
public void removeOnOffsetChangedListener(OnOffsetChangedListener listener) {
removeOnOffsetChangedListener((BaseOnOffsetChangedListener) listener);
}
/**
* Add a {@link LiftOnScrollListener} that will be called when the lift on scroll elevation and
* background color of this {@link AppBarLayout} change.
*/
public void addLiftOnScrollListener(@NonNull LiftOnScrollListener liftOnScrollListener) {
liftOnScrollListeners.add(liftOnScrollListener);
}
/** Remove a previously added {@link LiftOnScrollListener}. */
public boolean removeLiftOnScrollListener(@NonNull LiftOnScrollListener liftOnScrollListener) {
return liftOnScrollListeners.remove(liftOnScrollListener);
}
/** Remove all previously added {@link LiftOnScrollListener}s. */
public void clearLiftOnScrollListener() {
liftOnScrollListeners.clear();
}
/**
* Set the drawable to use for the status bar foreground drawable. Providing null will disable the
* scrim functionality.
*
* <p>This scrim is only shown when we have been given a top system inset.
*
* @param drawable the drawable to display
* @attr ref R.styleable#AppBarLayout_statusBarForeground
* @see #getStatusBarForeground()
*/
public void setStatusBarForeground(@Nullable Drawable drawable) {
if (statusBarForeground != drawable) {
if (statusBarForeground != null) {
statusBarForeground.setCallback(null);
}
statusBarForeground = drawable != null ? drawable.mutate() : null;
statusBarForegroundOriginalColor = extractStatusBarForegroundColor();
if (statusBarForeground != null) {
if (statusBarForeground.isStateful()) {
statusBarForeground.setState(getDrawableState());
}
DrawableCompat.setLayoutDirection(statusBarForeground, getLayoutDirection());
statusBarForeground.setVisible(getVisibility() == VISIBLE, false);
statusBarForeground.setCallback(this);
}
updateWillNotDraw();
postInvalidateOnAnimation();
}
}
/**
* Set the color to use for the status bar foreground.
*
* <p>This scrim is only shown when we have been given a top system inset.
*
* @param color the color to display
* @attr ref R.styleable#AppBarLayout_statusBarForeground
* @see #getStatusBarForeground()
*/
public void setStatusBarForegroundColor(@ColorInt int color) {
setStatusBarForeground(new ColorDrawable(color));
}
/**
* Set the drawable to use for the status bar foreground from resources.
*
* <p>This scrim is only shown when we have been given a top system inset.
*
* @param resId drawable resource id
* @attr ref R.styleable#AppBarLayout_statusBarForeground
* @see #getStatusBarForeground()
*/
public void setStatusBarForegroundResource(@DrawableRes int resId) {
setStatusBarForeground(AppCompatResources.getDrawable(getContext(), resId));
}
/**
* Returns the drawable which is used for the status bar foreground.
*
* @see #setStatusBarForeground(Drawable)
* @attr ref R.styleable#AppBarLayout_statusBarForeground
*/
@Nullable
public Drawable getStatusBarForeground() {
return statusBarForeground;
}
@Nullable
private Integer extractStatusBarForegroundColor() {
if (statusBarForeground instanceof MaterialShapeDrawable) {
return ((MaterialShapeDrawable) statusBarForeground).getResolvedTintColor();
}
ColorStateList statusBarForegroundColorStateList =
DrawableUtils.getColorStateListOrNull(statusBarForeground);
if (statusBarForegroundColorStateList != null) {
return statusBarForegroundColorStateList.getDefaultColor();
}
return null;
}
@Override
public void draw(@NonNull Canvas canvas) {
super.draw(canvas);
// Draw the status bar foreground drawable if we have a top inset
if (shouldDrawStatusBarForeground()) {
int saveCount = canvas.save();
canvas.translate(0f, -currentOffset);
statusBarForeground.draw(canvas);
canvas.restoreToCount(saveCount);
}
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
final int[] state = getDrawableState();
Drawable d = statusBarForeground;
if (d != null && d.isStateful() && d.setState(state)) {
invalidateDrawable(d);
}
}
@Override
protected boolean verifyDrawable(@NonNull Drawable who) {
return super.verifyDrawable(who) || who == statusBarForeground;
}
@Override
public void setVisibility(int visibility) {
super.setVisibility(visibility);
final boolean visible = visibility == VISIBLE;
if (statusBarForeground != null) {
statusBarForeground.setVisible(visible, false);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// If we're set to handle system windows but our first child is not, we need to add some
// height to ourselves to pad the first child down below the status bar
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
if (heightMode != MeasureSpec.EXACTLY && getFitsSystemWindows() && shouldOffsetFirstChild()) {
int newHeight = getMeasuredHeight();
switch (heightMode) {
case MeasureSpec.AT_MOST:
// For AT_MOST, we need to clamp our desired height with the max height
newHeight =
clamp(
getMeasuredHeight() + getTopInset(), 0, MeasureSpec.getSize(heightMeasureSpec));
break;
case MeasureSpec.UNSPECIFIED:
// For UNSPECIFIED we can use any height so just add the top inset
newHeight += getTopInset();
break;
case MeasureSpec.EXACTLY:
default: // fall out
}
setMeasuredDimension(getMeasuredWidth(), newHeight);
}
invalidateScrollRanges();
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
if (getFitsSystemWindows() && shouldOffsetFirstChild()) {
// If we need to offset the first child, we need to offset all of them to make space
final int topInset = getTopInset();
for (int z = getChildCount() - 1; z >= 0; z--) {
ViewCompat.offsetTopAndBottom(getChildAt(z), topInset);
}
}
invalidateScrollRanges();
haveChildWithInterpolator = false;
for (int i = 0, z = getChildCount(); i < z; i++) {
final View child = getChildAt(i);
final LayoutParams childLp = (LayoutParams) child.getLayoutParams();
final Interpolator interpolator = childLp.getScrollInterpolator();
if (interpolator != null) {
haveChildWithInterpolator = true;
break;
}
}
if (statusBarForeground != null) {
statusBarForeground.setBounds(0, 0, getWidth(), getTopInset());
}
// If the user has set liftable manually, don't set liftable state automatically.
if (!liftableOverride) {
setLiftableState(liftOnScroll || hasCollapsibleChild());
}
}
private void updateWillNotDraw() {
setWillNotDraw(!shouldDrawStatusBarForeground());
}
private boolean shouldDrawStatusBarForeground() {
return statusBarForeground != null && getTopInset() > 0;
}
private boolean hasCollapsibleChild() {
for (int i = 0, z = getChildCount(); i < z; i++) {
if (((LayoutParams) getChildAt(i).getLayoutParams()).isCollapsible()) {
return true;
}
}
return false;
}
private void invalidateScrollRanges() {
// Saves the current scrolling state when we need to recalculate scroll ranges
// If the total scroll range is not known yet, the ABL is never scrolled.
// If there's a pending action, we should skip this step and respect the pending action.
SavedState savedState =
behavior == null
|| totalScrollRange == INVALID_SCROLL_RANGE
|| pendingAction != PENDING_ACTION_NONE
? null : behavior.saveScrollState(AbsSavedState.EMPTY_STATE, this);
// Invalidate the scroll ranges
totalScrollRange = INVALID_SCROLL_RANGE;
downPreScrollRange = INVALID_SCROLL_RANGE;
downScrollRange = INVALID_SCROLL_RANGE;
// Restores the previous scrolling state. Don't override if there's a previously saved state
// which has not be restored yet. Multiple re-measuring can happen before the scroll state
// is actually restored. We don't want to restore the state in-between those re-measuring,
// since they can be incorrect.
if (savedState != null) {
behavior.restoreScrollState(savedState, false);
}
}
@Override
public void setOrientation(int orientation) {
if (orientation != VERTICAL) {
throw new IllegalArgumentException(
"AppBarLayout is always vertical and does not support horizontal orientation");
}
super.setOrientation(orientation);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
MaterialShapeUtils.setParentAbsoluteElevation(this);
}
@Override
@NonNull
public CoordinatorLayout.Behavior<AppBarLayout> getBehavior() {
behavior = new AppBarLayout.Behavior();
return behavior;
}
@Nullable
public MaterialShapeDrawable getMaterialShapeBackground() {
Drawable background = getBackground();
return background instanceof MaterialShapeDrawable ? (MaterialShapeDrawable) background : null;
}
@Override
public void setElevation(float elevation) {
super.setElevation(elevation);
MaterialShapeUtils.setElevation(this, elevation);
}
/**
* Sets whether this {@link AppBarLayout} is expanded or not, animating if it has already been
* laid out.
*
* <p>As with {@link AppBarLayout}'s scrolling, this method relies on this layout being a direct
* child of a {@link CoordinatorLayout}.
*
* @param expanded true if the layout should be fully expanded, false if it should be fully
* collapsed
* @attr ref com.google.android.material.R.styleable#AppBarLayout_expanded
*/
public void setExpanded(boolean expanded) {
setExpanded(expanded, isLaidOut());
}
/**
* Sets whether this {@link AppBarLayout} is expanded or not.
*
* <p>As with {@link AppBarLayout}'s scrolling, this method relies on this layout being a direct
* child of a {@link CoordinatorLayout}.
*
* @param expanded true if the layout should be fully expanded, false if it should be fully
* collapsed
* @param animate Whether to animate to the new state
* @attr ref com.google.android.material.R.styleable#AppBarLayout_expanded
*/
public void setExpanded(boolean expanded, boolean animate) {
setExpanded(expanded, animate, true);
}
private void setExpanded(boolean expanded, boolean animate, boolean force) {
pendingAction =
(expanded ? PENDING_ACTION_EXPANDED : PENDING_ACTION_COLLAPSED)
| (animate ? PENDING_ACTION_ANIMATE_ENABLED : 0)
| (force ? PENDING_ACTION_FORCE : 0);
requestLayout();
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof LayoutParams;
}
@Override
protected LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
}
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}
@Override
protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
if (p instanceof LinearLayout.LayoutParams) {
return new LayoutParams((LinearLayout.LayoutParams) p);
} else if (p instanceof MarginLayoutParams) {
return new LayoutParams((MarginLayoutParams) p);
}
return new LayoutParams(p);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
clearLiftOnScrollTargetView();
}
boolean hasChildWithInterpolator() {
return haveChildWithInterpolator;
}
/**
* Returns the scroll range of all children.
*
* @return the scroll range in px
*/
public final int getTotalScrollRange() {
if (totalScrollRange != INVALID_SCROLL_RANGE) {
return totalScrollRange;
}
int range = 0;
for (int i = 0, z = getChildCount(); i < z; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
// Gone views should not be included in the scroll range calculation.
continue;
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final int childHeight = child.getMeasuredHeight();
final int flags = lp.scrollFlags;
if ((flags & LayoutParams.SCROLL_FLAG_SCROLL) != 0) {
// We're set to scroll so add the child's height
range += childHeight + lp.topMargin + lp.bottomMargin;
if (i == 0 && child.getFitsSystemWindows()) {
// If this is the first child and it wants to handle system windows, we need to make
// sure we don't scroll it past the inset
range -= getTopInset();
}
if ((flags & LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED) != 0) {
// For a collapsing scroll, we to take the collapsed height into account.
// We also break straight away since later views can't scroll beneath
// us
range -= child.getMinimumHeight();
break;
}
} else {
// As soon as a view doesn't have the scroll flag, we end the range calculation.
// This is because views below can not scroll under a fixed view.
break;
}
}
return totalScrollRange = Math.max(0, range);
}
boolean hasScrollableChildren() {
return getTotalScrollRange() != 0;
}
/** Return the scroll range when scrolling up from a nested pre-scroll. */
int getUpNestedPreScrollRange() {
return getTotalScrollRange();
}
/** Return the scroll range when scrolling down from a nested pre-scroll. */
int getDownNestedPreScrollRange() {
if (downPreScrollRange != INVALID_SCROLL_RANGE) {
// If we already have a valid value, return it
return downPreScrollRange;
}
int range = 0;
for (int i = getChildCount() - 1; i >= 0; i--) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
// Gone views should not be included in the scroll range calculation.
continue;
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final int childHeight = child.getMeasuredHeight();
final int flags = lp.scrollFlags;
if ((flags & LayoutParams.FLAG_QUICK_RETURN) == LayoutParams.FLAG_QUICK_RETURN) {
// First take the margin into account
int childRange = lp.topMargin + lp.bottomMargin;
// The view has the quick return flag combination...
if ((flags & LayoutParams.SCROLL_FLAG_ENTER_ALWAYS_COLLAPSED) != 0) {
// If they're set to enter collapsed, use the minimum height
childRange += child.getMinimumHeight();
} else if ((flags & LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED) != 0) {
// Only enter by the amount of the collapsed height
childRange += childHeight - child.getMinimumHeight();
} else {
// Else use the full height
childRange += childHeight;
}
if (i == 0 && child.getFitsSystemWindows()) {
// If this is the first child and it wants to handle system windows, we need to make
// sure we don't scroll past the inset
childRange = Math.min(childRange, childHeight - getTopInset());
}
range += childRange;
} else if (range > 0) {
// If we've hit an non-quick return scrollable view, and we've already hit a
// quick return view, return now
break;
}
}
return downPreScrollRange = Math.max(0, range);
}
/** Return the scroll range when scrolling down from a nested scroll. */
int getDownNestedScrollRange() {
if (downScrollRange != INVALID_SCROLL_RANGE) {
// If we already have a valid value, return it
return downScrollRange;
}
int range = 0;
for (int i = 0, z = getChildCount(); i < z; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
// Gone views should not be included in the scroll range calculation.
continue;
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
int childHeight = child.getMeasuredHeight();
childHeight += lp.topMargin + lp.bottomMargin;
final int flags = lp.scrollFlags;
if ((flags & LayoutParams.SCROLL_FLAG_SCROLL) != 0) {
// We're set to scroll so add the child's height
range += childHeight;
if ((flags & LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED) != 0) {
// For a collapsing exit scroll, we to take the collapsed height into account.
// We also break the range straight away since later views can't scroll
// beneath us
range -= child.getMinimumHeight();
break;
}
} else {
// As soon as a view doesn't have the scroll flag, we end the range calculation.
// This is because views below can not scroll under a fixed view.
break;
}
}
return downScrollRange = Math.max(0, range);
}
void onOffsetChanged(int offset) {
currentOffset = offset;
if (!willNotDraw()) {
postInvalidateOnAnimation();
}
// Iterate backwards through the list so that most recently added listeners
// get the first chance to decide
if (listeners != null) {
for (int i = 0, z = listeners.size(); i < z; i++) {
final BaseOnOffsetChangedListener listener = listeners.get(i);
if (listener != null) {
listener.onOffsetChanged(this, offset);
}
}
}
}
public final int getMinimumHeightForVisibleOverlappingContent() {
final int topInset = getTopInset();
final int minHeight = getMinimumHeight();
if (minHeight != 0) {
// If this layout has a min height, use it (doubled)
return (minHeight * 2) + topInset;
}
// Otherwise, we'll use twice the min height of our last child
final int childCount = getChildCount();
final int lastChildMinHeight =
childCount >= 1 ? getChildAt(childCount - 1).getMinimumHeight() : 0;
if (lastChildMinHeight != 0) {
return (lastChildMinHeight * 2) + topInset;
}
// If we reach here then we don't have a min height explicitly set. Instead we'll take a
// guess at 1/3 of our height being visible
return getHeight() / 3;
}
@Override
protected int[] onCreateDrawableState(int extraSpace) {
if (tmpStatesArray == null) {
// Note that we can't allocate this at the class level (in declaration) since some paths in
// super View constructor are going to call this method before that
tmpStatesArray = new int[4];
}
final int[] extraStates = tmpStatesArray;
final int[] states = super.onCreateDrawableState(extraSpace + extraStates.length);
extraStates[0] = liftable ? R.attr.state_liftable : -R.attr.state_liftable;
extraStates[1] = liftable && lifted ? R.attr.state_lifted : -R.attr.state_lifted;
// Note that state_collapsible and state_collapsed are deprecated. This is to keep compatibility
// with existing state list animators that depend on these states.
extraStates[2] = liftable ? R.attr.state_collapsible : -R.attr.state_collapsible;
extraStates[3] = liftable && lifted ? R.attr.state_collapsed : -R.attr.state_collapsed;
return mergeDrawableStates(states, extraStates);
}
/**
* Sets whether the {@link AppBarLayout} is liftable or not.
*
* @return true if the liftable state changed
*/
public boolean setLiftable(boolean liftable) {
this.liftableOverride = true;
return setLiftableState(liftable);
}
/**
* Sets whether the {@link AppBarLayout} lifted state corresponding to {@link
* #setLiftable(boolean)} and {@link #setLifted(boolean)} will be overridden manually.
*
* <p>If true, this means that the {@link AppBarLayout} will not manage its own lifted state and
* it should instead be manually updated via {@link #setLifted(boolean)}. If false, the {@link
* AppBarLayout} will manage its lifted state based on the scrolling sibling view.
*
* <p>Note that calling {@link #setLiftable(boolean)} will result in this liftable override being
* enabled and set to true by default.
*/
public void setLiftableOverrideEnabled(boolean enabled) {
this.liftableOverride = enabled;
}
// Internal helper method that updates liftable state without enabling the override.
private boolean setLiftableState(boolean liftable) {
if (this.liftable != liftable) {
this.liftable = liftable;
refreshDrawableState();
return true;
}
return false;
}