/
BottomAppBar.java
1443 lines (1259 loc) · 52.7 KB
/
BottomAppBar.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.bottomappbar;
import com.google.android.material.R;
import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP;
import static com.google.android.material.shape.MaterialShapeDrawable.SHADOW_COMPAT_MODE_ALWAYS;
import static com.google.android.material.theme.overlay.MaterialThemeOverlay.wrap;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Parcel;
import android.os.Parcelable;
import androidx.appcompat.widget.ActionMenuView;
import androidx.appcompat.widget.Toolbar;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.ColorInt;
import androidx.annotation.Dimension;
import androidx.annotation.IntDef;
import androidx.annotation.MenuRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.Px;
import androidx.annotation.RestrictTo;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.coordinatorlayout.widget.CoordinatorLayout.AttachedBehavior;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.core.view.ViewCompat;
import androidx.core.view.ViewCompat.NestedScrollType;
import androidx.core.view.ViewCompat.ScrollAxis;
import androidx.core.view.WindowInsetsCompat;
import androidx.customview.view.AbsSavedState;
import com.google.android.material.animation.AnimationUtils;
import com.google.android.material.animation.TransformationCallback;
import com.google.android.material.behavior.HideBottomViewOnScrollBehavior;
import com.google.android.material.behavior.HideBottomViewOnScrollBehavior.OnScrollStateChangedListener;
import com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.floatingactionbutton.FloatingActionButton.OnVisibilityChangedListener;
import com.google.android.material.internal.ThemeEnforcement;
import com.google.android.material.internal.ViewUtils;
import com.google.android.material.internal.ViewUtils.RelativePadding;
import com.google.android.material.motion.MotionUtils;
import com.google.android.material.resources.MaterialResources;
import com.google.android.material.shape.EdgeTreatment;
import com.google.android.material.shape.MaterialShapeDrawable;
import com.google.android.material.shape.MaterialShapeUtils;
import com.google.android.material.shape.ShapeAppearanceModel;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
/**
* The Bottom App Bar is an extension of Toolbar that supports a shaped background that "cradles" an
* attached {@link FloatingActionButton}. A FAB is anchored to {@link BottomAppBar} by calling
* {@link CoordinatorLayout.LayoutParams#setAnchorId(int)}, or by setting {@code app:layout_anchor}
* on the FAB in xml.
*
* <p>Note: The Material Design Guidelines caution against using an {@link
* ExtendedFloatingActionButton} with a {@link BottomAppBar}, so there is limited support for that
* use case. {@link ExtendedFloatingActionButton} can be anchored to the {@link BottomAppBar}, but
* currently animations and the cutout are not supported.
*
* <p>There are two modes which determine where the FAB is shown relative to the {@link
* BottomAppBar}. {@link #FAB_ALIGNMENT_MODE_CENTER} mode is the primary mode with the FAB is
* centered. {@link #FAB_ALIGNMENT_MODE_END} is the secondary mode with the FAB on the side.
*
* <p>Do not use the {@code android:background} attribute or call {@code BottomAppBar.setBackground}
* because the BottomAppBar manages its background internally. Instead use {@code
* app:backgroundTint}.
*
* <p>To enable color theming for menu items you will also need to set the {@code
* materialThemeOverlay} attribute to a ThemeOverlay which sets the {@code colorControlNormal}
* attribute to the correct color. For example, if the background of the BottomAppBar is {@code
* colorSurface}, as it is in the default style, you should set {@code materialThemeOverlay} to
* {@code @style/ThemeOverlay.MaterialComponents.BottomAppBar.Surface}.
*
* @attr ref com.google.android.material.R.styleable#BottomAppBar_backgroundTint
* @attr ref com.google.android.material.R.styleable#BottomAppBar_fabAlignmentMode
* @attr ref com.google.android.material.R.styleable#BottomAppBar_fabAnchorMode
* @attr ref com.google.android.material.R.styleable#BottomAppBar_fabAnimationMode
* @attr ref com.google.android.material.R.styleable#BottomAppBar_fabCradleMargin
* @attr ref com.google.android.material.R.styleable#BottomAppBar_fabCradleRoundedCornerRadius
* @attr ref com.google.android.material.R.styleable#BottomAppBar_fabCradleVerticalOffset
* @attr ref com.google.android.material.R.styleable#BottomAppBar_hideOnScroll
* @attr ref com.google.android.material.R.styleable#BottomAppBar_paddingBottomSystemWindowInsets
*/
public class BottomAppBar extends Toolbar implements AttachedBehavior {
private static final int DEF_STYLE_RES = R.style.Widget_MaterialComponents_BottomAppBar;
private static final int FAB_ALIGNMENT_ANIM_DURATION_DEFAULT = 300;
private static final int FAB_ALIGNMENT_ANIM_DURATION_ATTR = R.attr.motionDurationLong2;
private static final int FAB_ALIGNMENT_ANIM_EASING_ATTR =
R.attr.motionEasingEmphasizedInterpolator;
private static final float FAB_ALIGNMENT_ANIM_EASING_MIDPOINT = .2F;
public static final int FAB_ALIGNMENT_MODE_CENTER = 0;
public static final int FAB_ALIGNMENT_MODE_END = 1;
/**
* The fabAlignmentMode determines the horizontal positioning of the cradle and the FAB which can
* be centered or aligned to the end.
*/
@IntDef({FAB_ALIGNMENT_MODE_CENTER, FAB_ALIGNMENT_MODE_END})
@Retention(RetentionPolicy.SOURCE)
public @interface FabAlignmentMode {}
/** The FAB is embedded inside the BottomAppBar. */
public static final int FAB_ANCHOR_MODE_EMBED = 0;
/** The FAB is cradled at the top of the BottomAppBar. */
public static final int FAB_ANCHOR_MODE_CRADLE = 1;
/**
* The fabAnchorMode determines the placement of the FAB within the BottomAppBar. The FAB can be
* cradled at the top of the BottomAppBar, or embedded within it.
*
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
@IntDef({FAB_ANCHOR_MODE_EMBED, FAB_ANCHOR_MODE_CRADLE})
@Retention(RetentionPolicy.SOURCE)
public @interface FabAnchorMode {}
public static final int FAB_ANIMATION_MODE_SCALE = 0;
public static final int FAB_ANIMATION_MODE_SLIDE = 1;
/**
* The fabAnimationMode determines the animation used to move the FAB between different alignment
* modes. Can be either scale, or slide. Scale mode will scale the fab down to a point and then
* scale it back in at it's new position. Slide mode will slide the fab from one position to the
* other.
*/
@IntDef({FAB_ANIMATION_MODE_SCALE, FAB_ANIMATION_MODE_SLIDE})
@Retention(RetentionPolicy.SOURCE)
public @interface FabAnimationMode {}
/** The menu items are aligned automatically to avoid the FAB. */
public static final int MENU_ALIGNMENT_MODE_AUTO = 0;
/** The menu items are aligned to the start. */
public static final int MENU_ALIGNMENT_MODE_START = 1;
/**
* The menuAlignmentMode determines the alignment of the menu items in the BottomAppBar.
*
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
@IntDef({MENU_ALIGNMENT_MODE_AUTO, MENU_ALIGNMENT_MODE_START})
@Retention(RetentionPolicy.SOURCE)
public @interface MenuAlignmentMode {}
@Nullable private Integer navigationIconTint;
private final int fabOffsetEndMode;
private final MaterialShapeDrawable materialShapeDrawable = new MaterialShapeDrawable();
@Nullable private Animator modeAnimator;
@Nullable private Animator menuAnimator;
@FabAlignmentMode private int fabAlignmentMode;
@FabAnimationMode private int fabAnimationMode;
@FabAnchorMode private int fabAnchorMode;
@MenuAlignmentMode private int menuAlignmentMode;
private boolean hideOnScroll;
private final boolean paddingBottomSystemWindowInsets;
private final boolean paddingLeftSystemWindowInsets;
private final boolean paddingRightSystemWindowInsets;
/** Keeps track of the number of currently running animations. */
private int animatingModeChangeCounter = 0;
private ArrayList<AnimationListener> animationListeners;
/**
* Track whether or not a new menu will be inflated along with a FAB alignment change. The
* inflation of the resource is deferred until an appropriate time during the FAB alignment/menu
* animation before being set and clearing this pending resource.
*/
private static final int NO_MENU_RES_ID = 0;
@MenuRes private int pendingMenuResId = NO_MENU_RES_ID;
private boolean menuAnimatingWithFabAlignmentMode = false;
/** Callback to be invoked when the BottomAppBar is animating. */
interface AnimationListener {
void onAnimationStart(BottomAppBar bar);
void onAnimationEnd(BottomAppBar bar);
}
/**
* If the {@link FloatingActionButton} is actually cradled in the {@link BottomAppBar} or if the
* {@link FloatingActionButton} is detached which will happen when the {@link
* FloatingActionButton} is not visible, or when the {@link BottomAppBar} is scrolled off the
* screen.
*/
private boolean fabAttached = true;
private Behavior behavior;
private int bottomInset;
private int rightInset;
private int leftInset;
/**
* Listens to the FABs hide or show animation to kick off an animation on BottomAppBar that reacts
* to the change.
*/
@NonNull
AnimatorListenerAdapter fabAnimationListener =
new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
// If the FAB has begun to animate as a result of the FAB alignment mode changing, the FAB
// alignment animation will handle coordination of menu animation and this should be
// skipped. If the FAB has begun to animate as a result of hiding/showing the FAB, the
// menu animation should be cancelled and restarted.
if (!menuAnimatingWithFabAlignmentMode) {
maybeAnimateMenuView(fabAlignmentMode, fabAttached);
}
}
};
/** Listens to any transformations applied to the FAB so the cutout can react. */
@NonNull
TransformationCallback<FloatingActionButton> fabTransformationCallback =
new TransformationCallback<FloatingActionButton>() {
@Override
public void onScaleChanged(@NonNull FloatingActionButton fab) {
materialShapeDrawable.setInterpolation(
fab.getVisibility() == View.VISIBLE && fabAnchorMode == FAB_ANCHOR_MODE_CRADLE
? fab.getScaleY()
: 0);
}
@Override
public void onTranslationChanged(@NonNull FloatingActionButton fab) {
if (fabAnchorMode != FAB_ANCHOR_MODE_CRADLE) {
return;
}
float horizontalOffset = fab.getTranslationX();
if (getTopEdgeTreatment().getHorizontalOffset() != horizontalOffset) {
getTopEdgeTreatment().setHorizontalOffset(horizontalOffset);
materialShapeDrawable.invalidateSelf();
}
// If the translation of the fab has changed, update the vertical offset.
float verticalOffset = Math.max(0, -fab.getTranslationY());
if (getTopEdgeTreatment().getCradleVerticalOffset() != verticalOffset) {
getTopEdgeTreatment().setCradleVerticalOffset(verticalOffset);
materialShapeDrawable.invalidateSelf();
}
materialShapeDrawable.setInterpolation(
fab.getVisibility() == View.VISIBLE ? fab.getScaleY() : 0);
}
};
public BottomAppBar(@NonNull Context context) {
this(context, null);
}
public BottomAppBar(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, R.attr.bottomAppBarStyle);
}
public BottomAppBar(@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();
TypedArray a =
ThemeEnforcement.obtainStyledAttributes(
context, attrs, R.styleable.BottomAppBar, defStyleAttr, DEF_STYLE_RES);
ColorStateList backgroundTint =
MaterialResources.getColorStateList(context, a, R.styleable.BottomAppBar_backgroundTint);
if (a.hasValue(R.styleable.BottomAppBar_navigationIconTint)) {
setNavigationIconTint(a.getColor(R.styleable.BottomAppBar_navigationIconTint, -1));
}
int elevation = a.getDimensionPixelSize(R.styleable.BottomAppBar_elevation, 0);
float fabCradleMargin = a.getDimensionPixelOffset(R.styleable.BottomAppBar_fabCradleMargin, 0);
float fabCornerRadius =
a.getDimensionPixelOffset(R.styleable.BottomAppBar_fabCradleRoundedCornerRadius, 0);
float fabVerticalOffset =
a.getDimensionPixelOffset(R.styleable.BottomAppBar_fabCradleVerticalOffset, 0);
fabAlignmentMode =
a.getInt(R.styleable.BottomAppBar_fabAlignmentMode, FAB_ALIGNMENT_MODE_CENTER);
fabAnimationMode =
a.getInt(R.styleable.BottomAppBar_fabAnimationMode, FAB_ANIMATION_MODE_SCALE);
fabAnchorMode = a.getInt(R.styleable.BottomAppBar_fabAnchorMode, FAB_ANCHOR_MODE_CRADLE);
menuAlignmentMode =
a.getInt(R.styleable.BottomAppBar_menuAlignmentMode, MENU_ALIGNMENT_MODE_AUTO);
hideOnScroll = a.getBoolean(R.styleable.BottomAppBar_hideOnScroll, false);
// Reading out if we are handling bottom padding, so we can apply it to the FAB.
paddingBottomSystemWindowInsets =
a.getBoolean(R.styleable.BottomAppBar_paddingBottomSystemWindowInsets, false);
paddingLeftSystemWindowInsets =
a.getBoolean(R.styleable.BottomAppBar_paddingLeftSystemWindowInsets, false);
paddingRightSystemWindowInsets =
a.getBoolean(R.styleable.BottomAppBar_paddingRightSystemWindowInsets, false);
a.recycle();
fabOffsetEndMode =
getResources().getDimensionPixelOffset(R.dimen.mtrl_bottomappbar_fabOffsetEndMode);
EdgeTreatment topEdgeTreatment =
new BottomAppBarTopEdgeTreatment(fabCradleMargin, fabCornerRadius, fabVerticalOffset);
ShapeAppearanceModel shapeAppearanceModel =
ShapeAppearanceModel.builder().setTopEdge(topEdgeTreatment).build();
materialShapeDrawable.setShapeAppearanceModel(shapeAppearanceModel);
materialShapeDrawable.setShadowCompatibilityMode(SHADOW_COMPAT_MODE_ALWAYS);
materialShapeDrawable.setPaintStyle(Style.FILL);
materialShapeDrawable.initializeElevationOverlay(context);
setElevation(elevation);
DrawableCompat.setTintList(materialShapeDrawable, backgroundTint);
ViewCompat.setBackground(this, materialShapeDrawable);
ViewUtils.doOnApplyWindowInsets(
this,
attrs,
defStyleAttr,
DEF_STYLE_RES,
new ViewUtils.OnApplyWindowInsetsListener() {
@NonNull
@Override
public WindowInsetsCompat onApplyWindowInsets(
View view,
@NonNull WindowInsetsCompat insets,
@NonNull RelativePadding initialPadding) {
// Just read the insets here. doOnApplyWindowInsets will apply the padding under the
// hood.
boolean leftInsetsChanged = false;
boolean rightInsetsChanged = false;
if (paddingBottomSystemWindowInsets) {
bottomInset = insets.getSystemWindowInsetBottom();
}
if (paddingLeftSystemWindowInsets) {
leftInsetsChanged = leftInset != insets.getSystemWindowInsetLeft();
leftInset = insets.getSystemWindowInsetLeft();
}
if (paddingRightSystemWindowInsets) {
rightInsetsChanged = rightInset != insets.getSystemWindowInsetRight();
rightInset = insets.getSystemWindowInsetRight();
}
// We may need to change the position of the cutout or the action menu if the side
// insets have changed.
if (leftInsetsChanged || rightInsetsChanged) {
cancelAnimations();
setCutoutStateAndTranslateFab();
setActionMenuViewPosition();
}
return insets;
}
});
}
@Override
public void setNavigationIcon(@Nullable Drawable drawable) {
super.setNavigationIcon(maybeTintNavigationIcon(drawable));
}
/**
* Sets the color of the toolbar's navigation icon.
*
* @see #setNavigationIcon
*/
public void setNavigationIconTint(@ColorInt int navigationIconTint) {
this.navigationIconTint = navigationIconTint;
Drawable navigationIcon = getNavigationIcon();
if (navigationIcon != null) {
// Causes navigation icon to be tinted if needed.
setNavigationIcon(navigationIcon);
}
}
/**
* Returns the current fabAlignmentMode, either {@link #FAB_ALIGNMENT_MODE_CENTER} or {@link
* #FAB_ALIGNMENT_MODE_END}.
*/
@FabAlignmentMode
public int getFabAlignmentMode() {
return fabAlignmentMode;
}
/**
* Sets the current {@code fabAlignmentMode}. An animated transition between current and desired
* modes will be played.
*
* @param fabAlignmentMode the desired fabAlignmentMode, either {@link #FAB_ALIGNMENT_MODE_CENTER}
* or {@link #FAB_ALIGNMENT_MODE_END}.
*/
public void setFabAlignmentMode(@FabAlignmentMode int fabAlignmentMode) {
setFabAlignmentModeAndReplaceMenu(fabAlignmentMode, NO_MENU_RES_ID);
}
/**
* Sets the current {@code fabAlignmentMode} and replaces the {@code BottomAppBar}'s menu
* resource. An animated transition between the current and desired mode will be played in
* coordination with a menu resource swap animation.
*
* @param fabAlignmentMode the desired fabAlignmentMode, either {@link #FAB_ALIGNMENT_MODE_CENTER}
* or {@link #FAB_ALIGNMENT_MODE_END}.
* @param newMenu the menu resource of a new menu to be inflated and swapped during the animation.
* Passing 0 for newMenu will not clear the menu but will skip all menu manipulation. If you'd
* like to animate the FAB's alignment and clear the menu at the same time, use {@code
* getMenu().clear()} and {@link #setFabAlignmentMode(int)}.
*/
public void setFabAlignmentModeAndReplaceMenu(
@FabAlignmentMode int fabAlignmentMode, @MenuRes int newMenu) {
this.pendingMenuResId = newMenu;
this.menuAnimatingWithFabAlignmentMode = true;
maybeAnimateMenuView(fabAlignmentMode, fabAttached);
maybeAnimateModeChange(fabAlignmentMode);
this.fabAlignmentMode = fabAlignmentMode;
}
/**
* Returns the current {@code fabAnchorMode}, either {@link #FAB_ANCHOR_MODE_CRADLE} or {@link
* #FAB_ANCHOR_MODE_EMBED}.
*/
@FabAnchorMode
public int getFabAnchorMode() {
return fabAnchorMode;
}
/**
* Sets the current {@code fabAnchorMode}.
*
* @param fabAnchorMode the desired fabAnchorMode, either {@link #FAB_ANCHOR_MODE_CRADLE} or
* {@link #FAB_ANCHOR_MODE_EMBED}.
*/
public void setFabAnchorMode(@FabAnchorMode int fabAnchorMode) {
this.fabAnchorMode = fabAnchorMode;
setCutoutStateAndTranslateFab();
View fab = findDependentView();
if (fab != null) {
updateFabAnchorGravity(this, fab);
fab.requestLayout();
materialShapeDrawable.invalidateSelf();
}
}
private static void updateFabAnchorGravity(BottomAppBar bar, View fab) {
CoordinatorLayout.LayoutParams fabLayoutParams =
(CoordinatorLayout.LayoutParams) fab.getLayoutParams();
fabLayoutParams.anchorGravity = Gravity.CENTER;
if (bar.fabAnchorMode == FAB_ANCHOR_MODE_CRADLE) {
fabLayoutParams.anchorGravity |= Gravity.TOP;
}
}
/**
* Returns the current {@code fabAnimationMode}, either {@link #FAB_ANIMATION_MODE_SCALE} or
* {@link #FAB_ANIMATION_MODE_SLIDE}.
*/
@FabAnimationMode
public int getFabAnimationMode() {
return fabAnimationMode;
}
/**
* Sets the current {@code fabAnimationMode}.
*
* @param fabAnimationMode the desired fabAlignmentMode, either {@link #FAB_ALIGNMENT_MODE_CENTER}
* or {@link #FAB_ALIGNMENT_MODE_END}.
*/
public void setFabAnimationMode(@FabAnimationMode int fabAnimationMode) {
this.fabAnimationMode = fabAnimationMode;
}
/**
* Sets the current {@code menuAlignmentMode}. Determines where the menu items in the BottomAppBar
* will be aligned.
*
* @param menuAlignmentMode the desired menuAlignmentMode, either {@link
* #MENU_ALIGNMENT_MODE_AUTO} or {@link #MENU_ALIGNMENT_MODE_START}.
*/
public void setMenuAlignmentMode(@MenuAlignmentMode int menuAlignmentMode) {
if (this.menuAlignmentMode != menuAlignmentMode) {
this.menuAlignmentMode = menuAlignmentMode;
ActionMenuView menu = getActionMenuView();
if (menu != null) {
translateActionMenuView(menu, fabAlignmentMode, isFabVisibleOrWillBeShown());
}
}
}
/**
* Returns the current menuAlignmentMode, either {@link #MENU_ALIGNMENT_MODE_AUTO} or {@link
* #MENU_ALIGNMENT_MODE_START}.
*/
@MenuAlignmentMode
public int getMenuAlignmentMode() {
return menuAlignmentMode;
}
public void setBackgroundTint(@Nullable ColorStateList backgroundTint) {
DrawableCompat.setTintList(materialShapeDrawable, backgroundTint);
}
@Nullable
public ColorStateList getBackgroundTint() {
return materialShapeDrawable.getTintList();
}
/**
* Returns the cradle margin for the fab cutout. This is the space between the fab and the cutout.
*/
public float getFabCradleMargin() {
return getTopEdgeTreatment().getFabCradleMargin();
}
/**
* Sets the cradle margin for the fab cutout.
*
* This is the space between the fab and the cutout. If
* the fab anchor mode is not cradled, this will not be respected.
*/
public void setFabCradleMargin(@Dimension float cradleMargin) {
if (cradleMargin != getFabCradleMargin()) {
getTopEdgeTreatment().setFabCradleMargin(cradleMargin);
materialShapeDrawable.invalidateSelf();
}
}
/**
* Returns the rounded corner radius for the cutout if it exists. A value of 0 will be a
* sharp edge.
*/
@Dimension
public float getFabCradleRoundedCornerRadius() {
return getTopEdgeTreatment().getFabCradleRoundedCornerRadius();
}
/**
* Sets the rounded corner radius for the fab cutout. A value of 0 will be a sharp edge.
* This will not be visible until there is a cradle.
*/
public void setFabCradleRoundedCornerRadius(@Dimension float roundedCornerRadius) {
if (roundedCornerRadius != getFabCradleRoundedCornerRadius()) {
getTopEdgeTreatment().setFabCradleRoundedCornerRadius(roundedCornerRadius);
materialShapeDrawable.invalidateSelf();
}
}
/**
* Returns the vertical offset for the fab cutout. An offset of 0 indicates the vertical center of
* the {@link FloatingActionButton} is positioned on the top edge.
*/
@Dimension
public float getCradleVerticalOffset() {
return getTopEdgeTreatment().getCradleVerticalOffset();
}
/**
* Sets the vertical offset, in pixels, of the {@link FloatingActionButton} being cradled. An
* offset of 0 indicates the vertical center of the {@link FloatingActionButton} is positioned on
* the top edge.
* This will not be visible until there is a cradle.
*/
public void setCradleVerticalOffset(@Dimension float verticalOffset) {
if (verticalOffset != getCradleVerticalOffset()) {
getTopEdgeTreatment().setCradleVerticalOffset(verticalOffset);
materialShapeDrawable.invalidateSelf();
setCutoutStateAndTranslateFab();
}
}
/**
* Returns true if the {@link BottomAppBar} should hide when a {@link
* androidx.core.view.NestedScrollingChild} is scrolled. This is handled by {@link
* BottomAppBar.Behavior}.
*/
public boolean getHideOnScroll() {
return hideOnScroll;
}
/**
* Sets if the {@link BottomAppBar} should hide when a {@link
* androidx.core.view.NestedScrollingChild} is scrolled. This is handled by {@link
* BottomAppBar.Behavior}.
*/
public void setHideOnScroll(boolean hide) {
hideOnScroll = hide;
}
/** Animates the {@link BottomAppBar} so it hides off the screen. */
public void performHide() {
performHide(/*animate=*/ true);
}
/**
* Hides the {@link BottomAppBar}.
*
* @param animate {@code false} to hide the {@link BottomAppBar} immediately without animation.
*/
public void performHide(boolean animate) {
getBehavior().slideDown(this, animate);
}
/** Animates the {@link BottomAppBar} so it is shown on the screen. */
public void performShow() {
performShow(/*animate=*/ true);
}
/**
* Shows the {@link BottomAppBar}.
*
* @param animate {@code false} to show the {@link BottomAppBar} immediately without animation.
*/
public void performShow(boolean animate) {
getBehavior().slideUp(this, animate);
}
/** Returns true if the {@link BottomAppBar} is scrolled down. */
public boolean isScrolledDown() {
return getBehavior().isScrolledDown();
}
/** Returns true if the {@link BottomAppBar} is scrolled up. */
public boolean isScrolledUp() {
return getBehavior().isScrolledUp();
}
/**
* Add a listener that will be called when the bottom app bar scroll state changes.
* See {@link OnScrollStateChangedListener}.
*
* <p>Components that add a listener should take care to remove it when finished via {@link
* #removeOnScrollStateChangedListener(OnScrollStateChangedListener)}.
*
* @param listener listener to add
*/
public void addOnScrollStateChangedListener(@NonNull OnScrollStateChangedListener listener) {
getBehavior().addOnScrollStateChangedListener(listener);
}
/**
* Remove a listener that was previously added via {@link
* #addOnScrollStateChangedListener(OnScrollStateChangedListener)}.
*
* @param listener listener to remove
*/
public void removeOnScrollStateChangedListener(
@NonNull OnScrollStateChangedListener listener) {
getBehavior().removeOnScrollStateChangedListener(listener);
}
/** Remove all previously added {@link OnScrollStateChangedListener}s. */
public void clearOnScrollStateChangedListeners() {
getBehavior().clearOnScrollStateChangedListeners();
}
@Override
public void setElevation(float elevation) {
materialShapeDrawable.setElevation(elevation);
// Make sure the shadow isn't shown if this view slides down with hideOnScroll.
int topShadowHeight =
materialShapeDrawable.getShadowRadius() - materialShapeDrawable.getShadowOffsetY();
getBehavior().setAdditionalHiddenOffsetY(this, topShadowHeight);
}
/**
* A convenience method to replace the contents of the BottomAppBar's menu.
*
* @param newMenu the desired new menu.
*/
public void replaceMenu(@MenuRes int newMenu) {
if (newMenu != NO_MENU_RES_ID) {
// Clear any pending menu changes if the menu being passed in happens to be pendingMenuResID.
pendingMenuResId = NO_MENU_RES_ID;
getMenu().clear();
inflateMenu(newMenu);
}
}
/** Add a listener to watch for animation changes to the BottomAppBar and FAB */
void addAnimationListener(@NonNull AnimationListener listener) {
if (animationListeners == null) {
animationListeners = new ArrayList<>();
}
animationListeners.add(listener);
}
void removeAnimationListener(@NonNull AnimationListener listener) {
if (animationListeners == null) {
return;
}
animationListeners.remove(listener);
}
private void dispatchAnimationStart() {
if (animatingModeChangeCounter++ == 0 && animationListeners != null) {
// Only dispatch the starting event if there are 0 running animations before this one starts.
for (AnimationListener listener : animationListeners) {
listener.onAnimationStart(this);
}
}
}
private void dispatchAnimationEnd() {
if (--animatingModeChangeCounter == 0 && animationListeners != null) {
// Only dispatch the ending event if there are 0 running animations after this one ends.
for (AnimationListener listener : animationListeners) {
listener.onAnimationEnd(this);
}
}
}
/**
* Sets the fab diameter. This will be called automatically by the {@link BottomAppBar.Behavior}
* if the fab is anchored to this {@link BottomAppBar}..
*/
boolean setFabDiameter(@Px int diameter) {
if (diameter != getTopEdgeTreatment().getFabDiameter()) {
getTopEdgeTreatment().setFabDiameter(diameter);
materialShapeDrawable.invalidateSelf();
return true;
}
return false;
}
void setFabCornerSize(@Dimension float radius) {
if (radius != getTopEdgeTreatment().getFabCornerRadius()) {
getTopEdgeTreatment().setFabCornerSize(radius);
materialShapeDrawable.invalidateSelf();
}
}
private void maybeAnimateModeChange(@FabAlignmentMode int targetMode) {
if (fabAlignmentMode == targetMode || !ViewCompat.isLaidOut(this)) {
return;
}
if (modeAnimator != null) {
modeAnimator.cancel();
}
List<Animator> animators = new ArrayList<>();
if (fabAnimationMode == FAB_ANIMATION_MODE_SLIDE) {
createFabTranslationXAnimation(targetMode, animators);
} else {
createFabDefaultXAnimation(targetMode, animators);
}
AnimatorSet set = new AnimatorSet();
set.playTogether(animators);
set.setInterpolator(
MotionUtils.resolveThemeInterpolator(
getContext(), FAB_ALIGNMENT_ANIM_EASING_ATTR, AnimationUtils.LINEAR_INTERPOLATOR));
modeAnimator = set;
modeAnimator.addListener(
new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
dispatchAnimationStart();
}
@Override
public void onAnimationEnd(Animator animation) {
dispatchAnimationEnd();
modeAnimator = null;
}
});
modeAnimator.start();
}
@Nullable
private FloatingActionButton findDependentFab() {
View view = findDependentView();
return view instanceof FloatingActionButton ? (FloatingActionButton) view : null;
}
@Nullable
private View findDependentView() {
if (!(getParent() instanceof CoordinatorLayout)) {
// If we aren't in a CoordinatorLayout we won't have a dependent FAB.
return null;
}
List<View> dependents = ((CoordinatorLayout) getParent()).getDependents(this);
for (View v : dependents) {
if (v instanceof FloatingActionButton || v instanceof ExtendedFloatingActionButton) {
return v;
}
}
return null;
}
private boolean isFabVisibleOrWillBeShown() {
FloatingActionButton fab = findDependentFab();
return fab != null && fab.isOrWillBeShown();
}
/**
* Creates the default animation for moving a fab between alignment modes. Can be overridden by
* extending classes to create a custom animation. Animations that should be executed should be
* added to the animators list. The default animation defined here calls {@link
* FloatingActionButton#hide()} and {@link FloatingActionButton#show()} rather than using custom
* animations.
*/
protected void createFabDefaultXAnimation(
final @FabAlignmentMode int targetMode, List<Animator> animators) {
final FloatingActionButton fab = findDependentFab();
if (fab == null || fab.isOrWillBeHidden()) {
return;
}
dispatchAnimationStart();
fab.hide(
new OnVisibilityChangedListener() {
@Override
public void onHidden(@NonNull FloatingActionButton fab) {
fab.setTranslationX(getFabTranslationX(targetMode));
fab.show(
new OnVisibilityChangedListener() {
@Override
public void onShown(FloatingActionButton fab) {
dispatchAnimationEnd();
}
});
}
});
}
private void createFabTranslationXAnimation(
@FabAlignmentMode int targetMode, @NonNull List<Animator> animators) {
ObjectAnimator animator =
ObjectAnimator.ofFloat(findDependentFab(), "translationX", getFabTranslationX(targetMode));
animator.setDuration(getFabAlignmentAnimationDuration());
animators.add(animator);
}
private int getFabAlignmentAnimationDuration() {
return MotionUtils.resolveThemeDuration(
getContext(), FAB_ALIGNMENT_ANIM_DURATION_ATTR, FAB_ALIGNMENT_ANIM_DURATION_DEFAULT);
}
@Nullable
private Drawable maybeTintNavigationIcon(@Nullable Drawable navigationIcon) {
if (navigationIcon != null && navigationIconTint != null) {
Drawable wrappedNavigationIcon = DrawableCompat.wrap(navigationIcon.mutate());
DrawableCompat.setTint(wrappedNavigationIcon, navigationIconTint);
return wrappedNavigationIcon;
} else {
return navigationIcon;
}
}
private void maybeAnimateMenuView(@FabAlignmentMode int targetMode, boolean newFabAttached) {
if (!ViewCompat.isLaidOut(this)) {
menuAnimatingWithFabAlignmentMode = false;
// If this method is called before the BottomAppBar is laid out and able to animate, make sure
// the desired menu is still set even if the animation is skipped.
replaceMenu(pendingMenuResId);
return;
}
if (menuAnimator != null) {
menuAnimator.cancel();
}
List<Animator> animators = new ArrayList<>();
// If there's no visible FAB, treat the animation like the FAB is going away.
if (!isFabVisibleOrWillBeShown()) {
targetMode = FAB_ALIGNMENT_MODE_CENTER;
newFabAttached = false;
}
createMenuViewTranslationAnimation(targetMode, newFabAttached, animators);
AnimatorSet set = new AnimatorSet();
set.playTogether(animators);
menuAnimator = set;
menuAnimator.addListener(
new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
dispatchAnimationStart();
}
@Override
public void onAnimationEnd(Animator animation) {
dispatchAnimationEnd();
menuAnimatingWithFabAlignmentMode = false;
menuAnimator = null;
}
});
menuAnimator.start();
}
private void createMenuViewTranslationAnimation(
@FabAlignmentMode final int targetMode,
final boolean targetAttached,
@NonNull List<Animator> animators) {
final ActionMenuView actionMenuView = getActionMenuView();
// Stop if there is no action menu view to animate
if (actionMenuView == null) {
return;
}
final float animationDuration = getFabAlignmentAnimationDuration();
Animator fadeIn = ObjectAnimator.ofFloat(actionMenuView, "alpha", 1);
fadeIn.setDuration((long) (animationDuration * (1F - FAB_ALIGNMENT_ANIM_EASING_MIDPOINT)));
float translationXDifference =
actionMenuView.getTranslationX()
- getActionMenuViewTranslationX(actionMenuView, targetMode, targetAttached);
// If the MenuView has moved at least a pixel we will need to animate it.
if (Math.abs(translationXDifference) > 1) {
// We need to fade the MenuView out and in because it's position is changing
Animator fadeOut = ObjectAnimator.ofFloat(actionMenuView, "alpha", 0);
fadeOut.setDuration((long) (animationDuration * FAB_ALIGNMENT_ANIM_EASING_MIDPOINT));
fadeOut.addListener(
new AnimatorListenerAdapter() {
public boolean cancelled;
@Override
public void onAnimationCancel(Animator animation) {
cancelled = true;
}
@Override
public void onAnimationEnd(Animator animation) {
if (!cancelled) {
boolean replaced = pendingMenuResId != NO_MENU_RES_ID;
replaceMenu(pendingMenuResId);
translateActionMenuView(actionMenuView, targetMode, targetAttached, replaced);
}
}
});
AnimatorSet set = new AnimatorSet();
set.playSequentially(fadeOut, fadeIn);
animators.add(set);
} else if (actionMenuView.getAlpha() < 1) {
// If the previous animation was cancelled in the middle and now we're deciding we don't need
// fade the MenuView away and back in, we need to ensure the MenuView is visible
animators.add(fadeIn);
}
}
private float getFabTranslationY() {
if (fabAnchorMode == FAB_ANCHOR_MODE_CRADLE) {
return -getTopEdgeTreatment().getCradleVerticalOffset();
}
return 0;
}
private float getFabTranslationX(@FabAlignmentMode int fabAlignmentMode) {
boolean isRtl = ViewUtils.isLayoutRtl(this);
if (fabAlignmentMode == FAB_ALIGNMENT_MODE_END) {
int systemEndInset = isRtl ? leftInset : rightInset;
int totalEndInset = fabOffsetEndMode + systemEndInset;
return (getMeasuredWidth() / 2 - totalEndInset) * (isRtl ? -1 : 1);
} else {