-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
FloatingActionButton.java
1484 lines (1300 loc) · 48.9 KB
/
FloatingActionButton.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.floatingactionbutton;
import com.google.android.material.R;
import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP;
import static androidx.core.util.Preconditions.checkNotNull;
import static com.google.android.material.theme.overlay.MaterialThemeOverlay.wrap;
import android.animation.Animator.AnimatorListener;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.PorterDuff.Mode;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Parcelable;
import androidx.appcompat.widget.AppCompatDrawableManager;
import androidx.appcompat.widget.AppCompatImageHelper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.AnimatorRes;
import androidx.annotation.ColorInt;
import androidx.annotation.DimenRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.IdRes;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.Px;
import androidx.annotation.RestrictTo;
import androidx.annotation.VisibleForTesting;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.core.view.TintableBackgroundView;
import androidx.core.view.ViewCompat;
import androidx.core.widget.TintableImageSourceView;
import com.google.android.material.animation.MotionSpec;
import com.google.android.material.animation.TransformationCallback;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.expandable.ExpandableTransformationWidget;
import com.google.android.material.expandable.ExpandableWidgetHelper;
import com.google.android.material.floatingactionbutton.FloatingActionButtonImpl.InternalTransformationCallback;
import com.google.android.material.floatingactionbutton.FloatingActionButtonImpl.InternalVisibilityChangedListener;
import com.google.android.material.internal.DescendantOffsetUtils;
import com.google.android.material.internal.ThemeEnforcement;
import com.google.android.material.internal.ViewUtils;
import com.google.android.material.internal.VisibilityAwareImageButton;
import com.google.android.material.resources.MaterialResources;
import com.google.android.material.shadow.ShadowViewDelegate;
import com.google.android.material.shape.ShapeAppearanceModel;
import com.google.android.material.shape.Shapeable;
import com.google.android.material.stateful.ExtendableSavedState;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.List;
/**
* Floating action buttons are used for a special type of promoted action. They are distinguished by
* a circled icon floating above the UI and have special motion behaviors related to morphing,
* launching, and the transferring anchor point.
*
* <p>Floating action buttons come in two sizes: the default and the mini. The size can be
* controlled with the {@code fabSize} attribute.
*
* <p>As this class descends from {@link ImageView}, you can control the icon which is displayed via
* {@link #setImageDrawable(Drawable)}.
*
* <p>The background color of this view defaults to the your theme's {@code colorSecondary}. If you
* wish to change this at runtime then you can do so via {@link
* #setBackgroundTintList(ColorStateList)}.
*
* <p>For more information, see the <a
* href="https://github.com/material-components/material-components-android/blob/master/docs/components/FloatingActionButton.md">component
* developer guidance</a> and <a
* href="https://material.io/components/floating-action-button/overview">design guidelines</a>.
*/
public class FloatingActionButton extends VisibilityAwareImageButton
implements TintableBackgroundView,
TintableImageSourceView,
ExpandableTransformationWidget,
Shapeable,
CoordinatorLayout.AttachedBehavior {
static final String ACCESSIBIILTY_FAB_ROLE =
"com.google.android.material.floatingactionbutton.FloatingActionButton";
private static final String LOG_TAG = "FloatingActionButton";
private static final String EXPANDABLE_WIDGET_HELPER_KEY = "expandableWidgetHelper";
private static final int DEF_STYLE_RES = R.style.Widget_Design_FloatingActionButton;
/** Callback to be invoked when the visibility of a FloatingActionButton changes. */
public abstract static class OnVisibilityChangedListener {
/**
* Called when a FloatingActionButton has been {@link #show(OnVisibilityChangedListener) shown}.
*
* @param fab the FloatingActionButton that was shown.
*/
public void onShown(FloatingActionButton fab) {}
/**
* Called when a FloatingActionButton has been {@link #hide(OnVisibilityChangedListener)
* hidden}.
*
* @param fab the FloatingActionButton that was hidden.
*/
public void onHidden(FloatingActionButton fab) {}
}
// These values must match those in the attrs declaration
/**
* The mini sized button, 40dp. Will always be smaller than {@link #SIZE_NORMAL}.
*
* @see #setSize(int)
*/
public static final int SIZE_MINI = 1;
/**
* The normal sized button, 56dp. Will always be larger than {@link #SIZE_MINI}.
*
* @see #setSize(int)
*/
public static final int SIZE_NORMAL = 0;
/**
* Size which will change based on the window size. For small sized windows (largest screen
* dimension < 470dp) this will select a mini sized button ({@link #SIZE_MINI}), and for larger
* sized windows it will select a normal sized button ({@link #SIZE_NORMAL}).
*
* @see #setSize(int)
*/
public static final int SIZE_AUTO = -1;
/**
* Indicates that the {@link FloatingActionButton} should not have a custom size, and instead that
* the size should be calculated based on the value set using {@link #setSize(int)} or the {@code
* fabSize} attribute. Instead of using this constant directly, you can call the {@link
* #clearCustomSize()} method.
*/
public static final int NO_CUSTOM_SIZE = 0;
/**
* The switch point for the largest screen edge where {@link #SIZE_AUTO} switches from mini to
* normal.
*/
private static final int AUTO_MINI_LARGEST_SCREEN_WIDTH = 470;
/** @hide */
@RestrictTo(LIBRARY_GROUP)
@Retention(RetentionPolicy.SOURCE)
@IntDef({SIZE_MINI, SIZE_NORMAL, SIZE_AUTO})
public @interface Size {}
@Nullable private ColorStateList backgroundTint;
@Nullable private PorterDuff.Mode backgroundTintMode;
@Nullable private ColorStateList imageTint;
@Nullable private PorterDuff.Mode imageMode;
@Nullable private ColorStateList rippleColor;
private int borderWidth;
private int size;
private int customSize;
private int imagePadding;
private int maxImageSize;
boolean compatPadding;
final Rect shadowPadding = new Rect();
private final Rect touchArea = new Rect();
@NonNull private final AppCompatImageHelper imageHelper;
@NonNull private final ExpandableWidgetHelper expandableWidgetHelper;
private FloatingActionButtonImpl impl;
public FloatingActionButton(@NonNull Context context) {
this(context, null);
}
public FloatingActionButton(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, R.attr.floatingActionButtonStyle);
}
@SuppressWarnings("nullness")
public FloatingActionButton(
@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.FloatingActionButton, defStyleAttr, DEF_STYLE_RES);
backgroundTint =
MaterialResources.getColorStateList(
context, a, R.styleable.FloatingActionButton_backgroundTint);
backgroundTintMode =
ViewUtils.parseTintMode(
a.getInt(R.styleable.FloatingActionButton_backgroundTintMode, -1), null);
rippleColor =
MaterialResources.getColorStateList(
context, a, R.styleable.FloatingActionButton_rippleColor);
size = a.getInt(R.styleable.FloatingActionButton_fabSize, SIZE_AUTO);
customSize =
a.getDimensionPixelSize(R.styleable.FloatingActionButton_fabCustomSize, NO_CUSTOM_SIZE);
borderWidth = a.getDimensionPixelSize(R.styleable.FloatingActionButton_borderWidth, 0);
final float elevation = a.getDimension(R.styleable.FloatingActionButton_elevation, 0f);
final float hoveredFocusedTranslationZ =
a.getDimension(R.styleable.FloatingActionButton_hoveredFocusedTranslationZ, 0f);
final float pressedTranslationZ =
a.getDimension(R.styleable.FloatingActionButton_pressedTranslationZ, 0f);
compatPadding = a.getBoolean(R.styleable.FloatingActionButton_useCompatPadding, false);
int minTouchTargetSize =
getResources().getDimensionPixelSize(R.dimen.mtrl_fab_min_touch_target);
setMaxImageSize(a.getDimensionPixelSize(R.styleable.FloatingActionButton_maxImageSize, 0));
MotionSpec showMotionSpec =
MotionSpec.createFromAttribute(context, a, R.styleable.FloatingActionButton_showMotionSpec);
MotionSpec hideMotionSpec =
MotionSpec.createFromAttribute(context, a, R.styleable.FloatingActionButton_hideMotionSpec);
ShapeAppearanceModel shapeAppearance =
ShapeAppearanceModel.builder(
context, attrs, defStyleAttr, DEF_STYLE_RES, ShapeAppearanceModel.PILL)
.build();
boolean ensureMinTouchTargetSize =
a.getBoolean(R.styleable.FloatingActionButton_ensureMinTouchTargetSize, false);
setEnabled(a.getBoolean(R.styleable.FloatingActionButton_android_enabled, true));
a.recycle();
imageHelper = new AppCompatImageHelper(this);
imageHelper.loadFromAttributes(attrs, defStyleAttr);
expandableWidgetHelper = new ExpandableWidgetHelper(this);
getImpl().setShapeAppearance(shapeAppearance);
getImpl()
.initializeBackgroundDrawable(backgroundTint, backgroundTintMode, rippleColor, borderWidth);
getImpl().setMinTouchTargetSize(minTouchTargetSize);
getImpl().setElevation(elevation);
getImpl().setHoveredFocusedTranslationZ(hoveredFocusedTranslationZ);
getImpl().setPressedTranslationZ(pressedTranslationZ);
getImpl().setShowMotionSpec(showMotionSpec);
getImpl().setHideMotionSpec(hideMotionSpec);
getImpl().setEnsureMinTouchTargetSize(ensureMinTouchTargetSize);
setScaleType(ScaleType.MATRIX);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int preferredSize = getSizeDimension();
imagePadding = (preferredSize - maxImageSize) / 2;
getImpl().updatePadding();
final int w = View.resolveSize(preferredSize, widthMeasureSpec);
final int h = View.resolveSize(preferredSize, heightMeasureSpec);
// As we want to stay circular, we set both dimensions to be the
// smallest resolved dimension
final int d = Math.min(w, h);
// We add the shadow's padding to the measured dimension
setMeasuredDimension(
d + shadowPadding.left + shadowPadding.right,
d + shadowPadding.top + shadowPadding.bottom);
}
/**
* Returns the ripple color for this button.
*
* @return the ARGB color used for the ripple
* @see #setRippleColor(int)
* @deprecated Use {@link #getRippleColorStateList()} instead.
*/
@ColorInt
@Deprecated
public int getRippleColor() {
return rippleColor != null ? rippleColor.getDefaultColor() : 0;
}
/**
* Returns the ripple color for this button.
*
* @return the color state list used for the ripple
* @see #setRippleColor(ColorStateList)
*/
@Nullable
public ColorStateList getRippleColorStateList() {
return rippleColor;
}
/**
* Sets the ripple color for this button.
*
* <p>When running on devices with KitKat, we draw this color as a filled circle rather
* than a ripple.
*
* @param color ARGB color to use for the ripple
* @attr ref com.google.android.material.R.styleable#FloatingActionButton_rippleColor
* @see #getRippleColor()
*/
public void setRippleColor(@ColorInt int color) {
setRippleColor(ColorStateList.valueOf(color));
}
/**
* Sets the ripple color for this button.
*
* <p>When running on devices with KitKat, we draw this color as a filled circle rather
* than a ripple.
*
* @param color color state list to use for the ripple
* @attr ref com.google.android.material.R.styleable#FloatingActionButton_rippleColor
* @see #getRippleColor()
*/
public void setRippleColor(@Nullable ColorStateList color) {
if (rippleColor != color) {
rippleColor = color;
getImpl().setRippleColor(rippleColor);
}
}
@Override
@NonNull
public CoordinatorLayout.Behavior<FloatingActionButton> getBehavior() {
return new FloatingActionButton.Behavior();
}
/**
* Returns the tint applied to the background drawable, if specified.
*
* @return the tint applied to the background drawable
* @see #setBackgroundTintList(ColorStateList)
*/
@Nullable
@Override
public ColorStateList getBackgroundTintList() {
return backgroundTint;
}
/**
* Applies a tint to the background drawable. Does not modify the current tint mode, which is
* {@link PorterDuff.Mode#SRC_IN} by default.
*
* @param tint the tint to apply, may be {@code null} to clear tint
*/
@Override
public void setBackgroundTintList(@Nullable ColorStateList tint) {
if (backgroundTint != tint) {
backgroundTint = tint;
getImpl().setBackgroundTintList(tint);
}
}
/**
* Returns the blending mode used to apply the tint to the background drawable, if specified.
*
* @return the blending mode used to apply the tint to the background drawable
* @see #setBackgroundTintMode(PorterDuff.Mode)
*/
@Nullable
@Override
public PorterDuff.Mode getBackgroundTintMode() {
return backgroundTintMode;
}
/**
* Specifies the blending mode used to apply the tint specified by {@link
* #setBackgroundTintList(ColorStateList)}} to the background drawable. The default mode is {@link
* PorterDuff.Mode#SRC_IN}.
*
* @param tintMode the blending mode used to apply the tint, may be {@code null} to clear tint
*/
@Override
public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
if (backgroundTintMode != tintMode) {
backgroundTintMode = tintMode;
getImpl().setBackgroundTintMode(tintMode);
}
}
/**
* Compat method to support {@link TintableBackgroundView}. Use {@link
* #setBackgroundTintList(ColorStateList)} directly instead.
*/
@Override
public void setSupportBackgroundTintList(@Nullable ColorStateList tint) {
setBackgroundTintList(tint);
}
/**
* Compat method to support {@link TintableBackgroundView}. Use {@link #getBackgroundTintList()}
* directly instead.
*/
@Nullable
@Override
public ColorStateList getSupportBackgroundTintList() {
return getBackgroundTintList();
}
/**
* Compat method to support {@link TintableBackgroundView}. Use {@link
* #setBackgroundTintMode(Mode)} directly instead.
*/
@Override
public void setSupportBackgroundTintMode(@Nullable Mode tintMode) {
setBackgroundTintMode(tintMode);
}
/**
* Compat method to support {@link TintableBackgroundView}. Use {@link #getBackgroundTintMode()}
* directly instead.
*/
@Nullable
@Override
public Mode getSupportBackgroundTintMode() {
return getBackgroundTintMode();
}
@Override
public void setSupportImageTintList(@Nullable ColorStateList tint) {
if (imageTint != tint) {
imageTint = tint;
onApplySupportImageTint();
}
}
@Nullable
@Override
public ColorStateList getSupportImageTintList() {
return imageTint;
}
@Override
public void setSupportImageTintMode(@Nullable Mode tintMode) {
if (imageMode != tintMode) {
imageMode = tintMode;
onApplySupportImageTint();
}
}
@Nullable
@Override
public Mode getSupportImageTintMode() {
return imageMode;
}
private void onApplySupportImageTint() {
Drawable drawable = getDrawable();
if (drawable == null) {
return;
}
if (imageTint == null) {
DrawableCompat.clearColorFilter(drawable);
return;
}
int color = imageTint.getColorForState(getDrawableState(), Color.TRANSPARENT);
Mode mode = imageMode;
if (mode == null) {
mode = Mode.SRC_IN;
}
drawable
.mutate()
.setColorFilter(AppCompatDrawableManager.getPorterDuffColorFilter(color, mode));
}
@Override
public void setBackgroundDrawable(Drawable background) {
Log.i(LOG_TAG, "Setting a custom background is not supported.");
}
@Override
public void setBackgroundResource(int resid) {
Log.i(LOG_TAG, "Setting a custom background is not supported.");
}
@Override
public void setBackgroundColor(int color) {
Log.i(LOG_TAG, "Setting a custom background is not supported.");
}
@Override
public void setImageResource(@DrawableRes int resId) {
// Intercept this call and instead retrieve the Drawable via the image helper
imageHelper.setImageResource(resId);
onApplySupportImageTint();
}
@Override
public void setImageDrawable(@Nullable Drawable drawable) {
if (getDrawable() != drawable) {
super.setImageDrawable(drawable);
getImpl().updateImageMatrixScale();
if (imageTint != null) {
onApplySupportImageTint();
}
}
}
/** Sets the {@link ShapeAppearanceModel} for this {@link FloatingActionButton}. */
@Override
public void setShapeAppearanceModel(@NonNull ShapeAppearanceModel shapeAppearance) {
getImpl().setShapeAppearance(shapeAppearance);
}
/** Returns the {@link ShapeAppearanceModel} for this {@link FloatingActionButton}. */
@Override
@NonNull
public ShapeAppearanceModel getShapeAppearanceModel() {
return checkNotNull(getImpl().getShapeAppearance());
}
/**
* Returns whether this fab will expand its bounds (if needed) to meet the minimum touch target
* size.
*
* @see #setEnsureMinTouchTargetSize(boolean)
* @attr ref com.google.android.material.R.styleable#FloatingActionButton_ensureMinTouchTargetSize
*/
public boolean shouldEnsureMinTouchTargetSize() {
return getImpl().getEnsureMinTouchTargetSize();
}
/**
* Sets whether this FloatingActionButton should expand its bounds (if needed) to meet the minimum
* touch target size.
*
* @attr ref com.google.android.material.R.styleable#FloatingActionButton_ensureMinTouchTargetSize
*/
public void setEnsureMinTouchTargetSize(boolean flag) {
if (flag != getImpl().getEnsureMinTouchTargetSize()) {
getImpl().setEnsureMinTouchTargetSize(flag);
requestLayout();
}
}
@Override
public void setVisibility(int visibility) {
super.setVisibility(visibility);
}
/**
* Sets the max image size for this button.
*
* @param imageSize maximum icon image size
* @attr ref com.google.android.material.R.styleable#FloatingActionButton_maxImageSize
*/
public void setMaxImageSize(int imageSize) {
maxImageSize = imageSize;
getImpl().setMaxImageSize(imageSize);
}
/**
* Shows the button.
*
* <p>This method will animate the button show if the view has already been laid out.
*/
public void show() {
show(null);
}
/**
* Shows the button.
*
* <p>This method will animate the button show if the view has already been laid out.
*
* @param listener the listener to notify when this view is shown
*/
public void show(@Nullable final OnVisibilityChangedListener listener) {
show(listener, true);
}
void show(@Nullable OnVisibilityChangedListener listener, boolean fromUser) {
getImpl().show(wrapOnVisibilityChangedListener(listener), fromUser);
}
public void addOnShowAnimationListener(@NonNull AnimatorListener listener) {
getImpl().addOnShowAnimationListener(listener);
}
public void removeOnShowAnimationListener(@NonNull AnimatorListener listener) {
getImpl().removeOnShowAnimationListener(listener);
}
/**
* Hides the button.
*
* <p>This method will animate the button hide if the view has already been laid out.
*/
public void hide() {
hide(null);
}
/**
* Hides the button.
*
* <p>This method will animate the button hide if the view has already been laid out.
*
* @param listener the listener to notify when this view is hidden
*/
public void hide(@Nullable OnVisibilityChangedListener listener) {
hide(listener, true);
}
void hide(@Nullable OnVisibilityChangedListener listener, boolean fromUser) {
getImpl().hide(wrapOnVisibilityChangedListener(listener), fromUser);
}
public void addOnHideAnimationListener(@NonNull AnimatorListener listener) {
getImpl().addOnHideAnimationListener(listener);
}
public void removeOnHideAnimationListener(@NonNull AnimatorListener listener) {
getImpl().removeOnHideAnimationListener(listener);
}
@Override
public boolean setExpanded(boolean expanded) {
return expandableWidgetHelper.setExpanded(expanded);
}
@Override
public boolean isExpanded() {
return expandableWidgetHelper.isExpanded();
}
@Override
public void setExpandedComponentIdHint(@IdRes int expandedComponentIdHint) {
expandableWidgetHelper.setExpandedComponentIdHint(expandedComponentIdHint);
}
@Override
public int getExpandedComponentIdHint() {
return expandableWidgetHelper.getExpandedComponentIdHint();
}
/**
* Set whether FloatingActionButton should add inner padding on platforms Lollipop and after, to
* ensure consistent dimensions on all platforms.
*
* @param useCompatPadding true if FloatingActionButton is adding inner padding on platforms
* Lollipop and after, to ensure consistent dimensions on all platforms.
* @attr ref com.google.android.material.R.styleable#FloatingActionButton_useCompatPadding
* @see #getUseCompatPadding()
*/
public void setUseCompatPadding(boolean useCompatPadding) {
if (compatPadding != useCompatPadding) {
compatPadding = useCompatPadding;
getImpl().onCompatShadowChanged();
}
}
/**
* Returns whether FloatingActionButton will add inner padding on platforms Lollipop and after.
*
* @return true if FloatingActionButton is adding inner padding on platforms Lollipop and after,
* to ensure consistent dimensions on all platforms.
* @attr ref com.google.android.material.R.styleable#FloatingActionButton_useCompatPadding
* @see #setUseCompatPadding(boolean)
*/
public boolean getUseCompatPadding() {
return compatPadding;
}
/**
* Sets the size of the button.
*
* <p>The options relate to the options available on the material design specification. {@link
* #SIZE_NORMAL} is larger than {@link #SIZE_MINI}. {@link #SIZE_AUTO} will choose an appropriate
* size based on the screen size.
*
* <p>Calling this method will turn off custom sizing (see {@link #setCustomSize(int)}) if it was
* previously on.
*
* @param size one of {@link #SIZE_NORMAL}, {@link #SIZE_MINI} or {@link #SIZE_AUTO}
* @attr ref com.google.android.material.R.styleable#FloatingActionButton_fabSize
*/
public void setSize(@Size int size) {
customSize = NO_CUSTOM_SIZE;
if (size != this.size) {
this.size = size;
requestLayout();
}
}
/**
* Returns the chosen size for this button.
*
* @return one of {@link #SIZE_NORMAL}, {@link #SIZE_MINI} or {@link #SIZE_AUTO}
* @see #setSize(int)
*/
@Size
public int getSize() {
return size;
}
@Nullable
private InternalVisibilityChangedListener wrapOnVisibilityChangedListener(
@Nullable final OnVisibilityChangedListener listener) {
if (listener == null) {
return null;
}
return new InternalVisibilityChangedListener() {
@Override
public void onShown() {
listener.onShown(FloatingActionButton.this);
}
@Override
public void onHidden() {
listener.onHidden(FloatingActionButton.this);
}
};
}
public boolean isOrWillBeHidden() {
return getImpl().isOrWillBeHidden();
}
public boolean isOrWillBeShown() {
return getImpl().isOrWillBeShown();
}
/**
* Sets the size of the button to be a custom value in pixels.
*
* <p>If you've set a custom size and would like to clear it, you can use the {@link
* #clearCustomSize()} method. If called, custom sizing will not be used and the size will be
* calculated based on the value set using {@link #setSize(int)} or the {@code fabSize} attribute.
*
* @param size preferred size in pixels, or {@link #NO_CUSTOM_SIZE}
* @attr ref com.google.android.material.R.styleable#FloatingActionButton_fabCustomSize
*/
public void setCustomSize(@Px int size) {
if (size < 0) {
throw new IllegalArgumentException("Custom size must be non-negative");
}
if (size != customSize) {
customSize = size;
requestLayout();
}
}
/**
* Returns the custom size for this {@link FloatingActionButton}.
*
* @return size in pixels, or {@link #NO_CUSTOM_SIZE}
*/
@Px
public int getCustomSize() {
return customSize;
}
/**
* Clears the custom size for this {@link FloatingActionButton}.
*
* <p>If called, custom sizing will not be used and the size will be calculated based on the value
* set using {@link #setSize(int)} or the {@code fabSize} attribute
*/
public void clearCustomSize() {
setCustomSize(NO_CUSTOM_SIZE);
}
int getSizeDimension() {
return getSizeDimension(size);
}
private int getSizeDimension(@Size final int size) {
if (customSize != NO_CUSTOM_SIZE) {
return customSize;
}
final Resources res = getResources();
switch (size) {
case SIZE_AUTO:
// If we're set to auto, grab the size from resources and refresh
final int width = res.getConfiguration().screenWidthDp;
final int height = res.getConfiguration().screenHeightDp;
return Math.max(width, height) < AUTO_MINI_LARGEST_SCREEN_WIDTH
? getSizeDimension(SIZE_MINI)
: getSizeDimension(SIZE_NORMAL);
case SIZE_MINI:
return res.getDimensionPixelSize(R.dimen.design_fab_size_mini);
case SIZE_NORMAL:
default:
return res.getDimensionPixelSize(R.dimen.design_fab_size_normal);
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
getImpl().onAttachedToWindow();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
getImpl().onDetachedFromWindow();
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
getImpl().onDrawableStateChanged(getDrawableState());
}
@Override
public void jumpDrawablesToCurrentState() {
super.jumpDrawablesToCurrentState();
getImpl().jumpDrawableToCurrentState();
}
@Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
if (superState == null) {
superState = new Bundle();
}
ExtendableSavedState state = new ExtendableSavedState(superState);
state.extendableStates.put(
EXPANDABLE_WIDGET_HELPER_KEY, expandableWidgetHelper.onSaveInstanceState());
return state;
}
@Override
@SuppressWarnings("nullness:argument")
// onRestoreInstanceState should accept nullable
protected void onRestoreInstanceState(Parcelable state) {
if (!(state instanceof ExtendableSavedState)) {
super.onRestoreInstanceState(state);
return;
}
ExtendableSavedState ess = (ExtendableSavedState) state;
super.onRestoreInstanceState(ess.getSuperState());
expandableWidgetHelper.onRestoreInstanceState(
checkNotNull(ess.extendableStates.get(EXPANDABLE_WIDGET_HELPER_KEY)));
}
/**
* Return in {@code rect} the bounds of the actual floating action button content in view-local
* coordinates. This is defined as anything within any visible shadow.
*
* @return true if this view actually has been laid out and has a content rect, else false.
* @deprecated prefer {@link FloatingActionButton#getMeasuredContentRect} instead, so you don't
* need to handle the case where the view isn't laid out.
*/
@Deprecated
public boolean getContentRect(@NonNull Rect rect) {
if (isLaidOut()) {
rect.set(0, 0, getWidth(), getHeight());
offsetRectWithShadow(rect);
return true;
} else {
return false;
}
}
/**
* Return in {@code rect} the bounds of the actual floating action button content in view-local
* coordinates. This is defined as anything within any visible shadow.
*/
public void getMeasuredContentRect(@NonNull Rect rect) {
rect.set(0, 0, getMeasuredWidth(), getMeasuredHeight());
offsetRectWithShadow(rect);
}
private void getTouchTargetRect(@NonNull Rect rect) {
getMeasuredContentRect(rect);
int touchTargetPadding = impl.getTouchTargetPadding();
rect.inset(-touchTargetPadding, -touchTargetPadding);
}
private void offsetRectWithShadow(@NonNull Rect rect) {
rect.left += shadowPadding.left;
rect.top += shadowPadding.top;
rect.right -= shadowPadding.right;
rect.bottom -= shadowPadding.bottom;
}
/** Returns the FloatingActionButton's background, minus any compatible shadow implementation. */
@Nullable
public Drawable getContentBackground() {
return getImpl().getContentBackground();
}
@Override
public boolean onTouchEvent(@NonNull MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
// Skipping the gesture if it doesn't start in the FAB 'content' area
getTouchTargetRect(touchArea);
if (!touchArea.contains((int) ev.getX(), (int) ev.getY())) {
return false;
}
}
return super.onTouchEvent(ev);
}
@Override
public CharSequence getAccessibilityClassName() {
return ACCESSIBIILTY_FAB_ROLE;
}
/**
* Behavior designed for use with {@link FloatingActionButton} instances. Its main function is to
* move {@link FloatingActionButton} views so that any displayed {@link
* com.google.android.material.snackbar.Snackbar}s do not cover them.
*/
// TODO(b/76413401): remove this generic type after the widget migration is done
public static class Behavior extends BaseBehavior<FloatingActionButton> {
public Behavior() {
super();
}
public Behavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
}
/**
* Behavior designed for use with {@link FloatingActionButton} instances. Its main function is to
* move {@link FloatingActionButton} views so that any displayed {@link
* com.google.android.material.snackbar.Snackbar}s do not cover them.
*/
// TODO(b/76413401): remove this generic type after the widget migration is done
protected static class BaseBehavior<T extends FloatingActionButton>
extends CoordinatorLayout.Behavior<T> {
private static final boolean AUTO_HIDE_DEFAULT = true;
private Rect tmpRect;
private OnVisibilityChangedListener internalAutoHideListener;
private boolean autoHideEnabled;
public BaseBehavior() {
super();
autoHideEnabled = AUTO_HIDE_DEFAULT;
}
public BaseBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a =
context.obtainStyledAttributes(attrs, R.styleable.FloatingActionButton_Behavior_Layout);
autoHideEnabled =
a.getBoolean(
R.styleable.FloatingActionButton_Behavior_Layout_behavior_autoHide,
AUTO_HIDE_DEFAULT);
a.recycle();
}
/**
* Sets whether the associated FloatingActionButton automatically hides when there is not enough
* space to be displayed. This works with {@link AppBarLayout} and {@link BottomSheetBehavior}.
*
* @attr ref
* com.google.android.material.R.styleable#FloatingActionButton_Behavior_Layout_behavior_autoHide
* @param autoHide true to enable automatic hiding
*/
public void setAutoHideEnabled(boolean autoHide) {
autoHideEnabled = autoHide;
}