-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Expand file tree
/
Copy pathNavigationBarItemView.java
More file actions
1527 lines (1364 loc) · 58.2 KB
/
Copy pathNavigationBarItemView.java
File metadata and controls
1527 lines (1364 loc) · 58.2 KB
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) 2020 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.navigation;
import com.google.android.material.R;
import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP;
import static com.google.android.material.navigation.NavigationBarView.ACTIVE_INDICATOR_WIDTH_MATCH_PARENT;
import static com.google.android.material.navigation.NavigationBarView.ACTIVE_INDICATOR_WIDTH_WRAP_CONTENT;
import static com.google.android.material.navigation.NavigationBarView.ITEM_ICON_GRAVITY_START;
import static com.google.android.material.navigation.NavigationBarView.ITEM_ICON_GRAVITY_TOP;
import static java.lang.Math.max;
import static java.lang.Math.min;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.RippleDrawable;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import androidx.appcompat.view.menu.MenuItemImpl;
import androidx.appcompat.widget.TooltipCompat;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.DimenRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.FloatRange;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.Px;
import androidx.annotation.RestrictTo;
import androidx.annotation.StyleRes;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat;
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat;
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat.CollectionItemInfoCompat;
import androidx.core.widget.TextViewCompat;
import com.google.android.material.animation.AnimationUtils;
import com.google.android.material.badge.BadgeDrawable;
import com.google.android.material.badge.BadgeUtils;
import com.google.android.material.focus.FocusRingDrawable;
import com.google.android.material.internal.BaselineLayout;
import com.google.android.material.motion.MotionUtils;
import com.google.android.material.navigation.NavigationBarView.ItemGravity;
import com.google.android.material.navigation.NavigationBarView.ItemIconGravity;
import com.google.android.material.resources.MaterialResources;
import com.google.android.material.ripple.RippleUtils;
import com.google.android.material.shape.MaterialShapeDrawable;
/**
* Provides a view that will be used to render destination items inside a {@link
* NavigationBarMenuView}.
*
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
public abstract class NavigationBarItemView extends FrameLayout
implements NavigationBarMenuItemView {
private static final int INVALID_ITEM_POSITION = -1;
private static final int[] CHECKED_STATE_SET = {android.R.attr.state_checked};
private boolean initialized = false;
private ColorStateList itemRippleColor;
@Nullable Drawable itemBackground;
private int itemPaddingTop;
private int itemPaddingBottom;
private int activeIndicatorLabelPadding;
private int iconLabelHorizontalSpacing;
private float shiftAmountY;
private float scaleUpFactor;
private float scaleDownFactor;
private float expandedLabelShiftAmountY;
private float expandedLabelScaleUpFactor;
private float expandedLabelScaleDownFactor;
private int labelVisibilityMode;
private boolean isShifting;
@NonNull private final LinearLayout contentContainer;
@NonNull private final LinearLayout innerContentContainer;
@NonNull private final View activeIndicatorView;
@NonNull private final FrameLayout iconContainer;
private final ImageView icon;
private final BaselineLayout labelGroup;
private final TextView smallLabel;
private final TextView largeLabel;
private BaselineLayout expandedLabelGroup;
private TextView expandedSmallLabel;
private TextView expandedLargeLabel;
private BaselineLayout currentLabelGroup;
private int itemPosition = INVALID_ITEM_POSITION;
@StyleRes private int textAppearanceActive = 0;
@StyleRes private int textAppearanceInactive = 0;
@StyleRes private int horizontalTextAppearanceActive = 0;
@StyleRes private int horizontalTextAppearanceInactive = 0;
@Nullable private ColorStateList textColor;
private boolean boldText = false;
@Nullable private MenuItemImpl itemData;
@Nullable private ColorStateList iconTint;
@Nullable private Drawable originalIconDrawable;
@Nullable private Drawable wrappedIconDrawable;
private static final ActiveIndicatorTransform ACTIVE_INDICATOR_LABELED_TRANSFORM =
new ActiveIndicatorTransform();
private static final ActiveIndicatorTransform ACTIVE_INDICATOR_UNLABELED_TRANSFORM =
new ActiveIndicatorUnlabeledTransform();
private ValueAnimator activeIndicatorAnimator;
private ActiveIndicatorTransform activeIndicatorTransform = ACTIVE_INDICATOR_LABELED_TRANSFORM;
private float activeIndicatorProgress = 0F;
private boolean activeIndicatorEnabled = false;
// The desired width of the indicator. This is not necessarily the actual size of the rendered
// indicator depending on whether the width of this view is wide enough to accommodate the full
// desired width.
private int activeIndicatorDesiredWidth = 0;
private int activeIndicatorDesiredHeight = 0;
private int activeIndicatorExpandedDesiredWidth = ACTIVE_INDICATOR_WIDTH_WRAP_CONTENT;
private int activeIndicatorExpandedDesiredHeight = 0;
private boolean activeIndicatorResizeable = false;
// The margin from the start and end of this view which the active indicator should respect. If
// the indicator width is greater than the total width minus the horizontal margins, the active
// indicator will assume the max width of the view's total width minus horizontal margins.
private int activeIndicatorMarginHorizontal = 0;
private int activeIndicatorExpandedMarginHorizontal = 0;
@Nullable private BadgeDrawable badgeDrawable;
@Nullable private CharSequence tooltipText;
@Nullable private OnLongClickListener customOnLongClickListener;
private boolean settingTooltipCompatLongClickListener;
@ItemIconGravity private int itemIconGravity;
private int badgeFixedEdge = BadgeDrawable.BADGE_FIXED_EDGE_START;
@ItemGravity private int itemGravity = NavigationBarView.ITEM_GRAVITY_TOP_CENTER;
private boolean expanded = false;
private boolean onlyShowWhenExpanded = false;
private boolean measurePaddingFromBaseline = false;
private boolean scaleLabelSizeWithFont = false;
private Rect itemActiveIndicatorExpandedPadding = new Rect();
public NavigationBarItemView(@NonNull Context context) {
super(context);
LayoutInflater.from(context).inflate(getItemLayoutResId(), this, true);
contentContainer = findViewById(R.id.navigation_bar_item_content_container);
innerContentContainer = findViewById(R.id.navigation_bar_item_inner_content_container);
activeIndicatorView = findViewById(R.id.navigation_bar_item_active_indicator_view);
iconContainer = findViewById(R.id.navigation_bar_item_icon_container);
icon = findViewById(R.id.navigation_bar_item_icon_view);
labelGroup = findViewById(R.id.navigation_bar_item_labels_group);
smallLabel = findViewById(R.id.navigation_bar_item_small_label_view);
largeLabel = findViewById(R.id.navigation_bar_item_large_label_view);
initializeDefaultExpandedLabelGroupViews();
currentLabelGroup = labelGroup;
setBackgroundResource(getItemBackgroundResId());
itemPaddingTop = getResources().getDimensionPixelSize(getItemDefaultMarginResId());
itemPaddingBottom = labelGroup.getPaddingBottom();
activeIndicatorLabelPadding = 0;
iconLabelHorizontalSpacing = 0;
// The labels used aren't always visible, so they are unreliable for accessibility. Instead,
// the content description of the NavigationBarItemView should be used for accessibility.
smallLabel.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
largeLabel.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
expandedSmallLabel.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
expandedLargeLabel.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
setFocusable(true);
calculateTextScaleFactors();
activeIndicatorExpandedDesiredHeight = getResources().getDimensionPixelSize(
R.dimen.m3_navigation_item_expanded_active_indicator_height_default);
// TODO(b/138148581): Support displaying a badge on label-only bottom navigation views.
innerContentContainer.addOnLayoutChangeListener(
(v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
if (icon.getVisibility() == VISIBLE) {
tryUpdateBadgeBounds(icon);
}
LayoutParams lp = (LayoutParams) innerContentContainer.getLayoutParams();
int newWidth = right - left + lp.rightMargin + lp.leftMargin;
int newHeight = bottom - top + lp.topMargin + lp.bottomMargin;
// If item icon gravity is start, we want to update the active indicator width in a layout
// change listener to keep the active indicator size up to date with the content width.
if (itemIconGravity == ITEM_ICON_GRAVITY_START
&& activeIndicatorExpandedDesiredWidth == ACTIVE_INDICATOR_WIDTH_WRAP_CONTENT) {
LayoutParams indicatorParams = (LayoutParams) activeIndicatorView.getLayoutParams();
boolean layoutParamsChanged = false;
if (activeIndicatorExpandedDesiredWidth == ACTIVE_INDICATOR_WIDTH_WRAP_CONTENT
&& activeIndicatorView.getMeasuredWidth() != newWidth) {
int minWidth =
min(
activeIndicatorDesiredWidth,
getMeasuredWidth() - (activeIndicatorMarginHorizontal * 2));
indicatorParams.width = max(newWidth, minWidth);
layoutParamsChanged = true;
}
// We expect the active indicator height to be larger than the height of the
// inner content due to having a min height, but if it is smaller (for example due to
// the text content changing to be multi-line) it should encompass that
if (activeIndicatorView.getMeasuredHeight() < newHeight) {
indicatorParams.height = newHeight;
layoutParamsChanged = true;
}
if (layoutParamsChanged) {
activeIndicatorView.setLayoutParams(indicatorParams);
}
}
});
}
@Override
protected int getSuggestedMinimumWidth() {
if (itemIconGravity == ITEM_ICON_GRAVITY_START) {
// Badge widths are not included for the start icon gravity config as we only want to measure
// the core content.
LayoutParams innerContentParams = (LayoutParams) innerContentContainer.getLayoutParams();
return innerContentContainer.getMeasuredWidth()
+ innerContentParams.leftMargin
+ innerContentParams.rightMargin;
}
LinearLayout.LayoutParams labelGroupParams =
(LinearLayout.LayoutParams) labelGroup.getLayoutParams();
int labelWidth =
labelGroupParams.leftMargin + labelGroup.getMeasuredWidth() + labelGroupParams.rightMargin;
return max(getSuggestedIconWidth(), labelWidth);
}
@Override
protected int getSuggestedMinimumHeight() {
LayoutParams contentContainerParams = (LayoutParams) contentContainer.getLayoutParams();
return contentContainer.getMeasuredHeight()
+ contentContainerParams.topMargin
+ contentContainerParams.bottomMargin;
}
@Override
public void initialize(@NonNull MenuItemImpl itemData, int menuType) {
this.itemData = itemData;
setCheckable(itemData.isCheckable());
setChecked(itemData.isChecked());
setEnabled(itemData.isEnabled());
setIcon(itemData.getIcon());
setTitle(itemData.getTitle());
setId(itemData.getItemId());
if (!TextUtils.isEmpty(itemData.getContentDescription())) {
setContentDescription(itemData.getContentDescription());
}
CharSequence tooltipText =
!TextUtils.isEmpty(itemData.getTooltipText())
? itemData.getTooltipText()
: itemData.getTitle();
setItemTooltipText(tooltipText);
updateVisibility();
this.initialized = true;
}
private void updateVisibility() {
if (itemData != null) {
setVisibility(
itemData.isVisible() && (expanded || !onlyShowWhenExpanded) ? View.VISIBLE : View.GONE);
}
}
/**
* Remove state so this View can be reused.
*
* <p>Item Views are held in a pool and reused when the number of menu items to be shown changes.
* This will be called when this View is released from the pool.
*
* @see NavigationBarMenuView#buildMenuView()
*/
void clear() {
this.removeBadge();
this.itemData = null;
this.activeIndicatorProgress = 0;
this.initialized = false;
}
public void setItemPosition(int position) {
itemPosition = position;
}
public int getItemPosition() {
return itemPosition;
}
@NonNull
public BaselineLayout getLabelGroup() {
return labelGroup;
}
@NonNull
public BaselineLayout getExpandedLabelGroup() {
return expandedLabelGroup;
}
public void setShifting(boolean shifting) {
if (isShifting != shifting) {
isShifting = shifting;
refreshChecked();
}
}
public void setLabelVisibilityMode(@NavigationBarView.LabelVisibility int mode) {
if (labelVisibilityMode != mode) {
labelVisibilityMode = mode;
updateActiveIndicatorTransform();
updateActiveIndicatorLayoutParams(getWidth());
refreshChecked();
}
}
private void initializeDefaultExpandedLabelGroupViews() {
float defaultInactiveTextSize =
getResources().getDimension(R.dimen.default_navigation_text_size);
float defaultActiveTextSize =
getResources().getDimension(R.dimen.default_navigation_active_text_size);
expandedLabelGroup = new BaselineLayout(getContext());
expandedLabelGroup.setVisibility(GONE);
expandedLabelGroup.setDuplicateParentStateEnabled(true);
expandedLabelGroup.setMeasurePaddingFromBaseline(measurePaddingFromBaseline);
expandedSmallLabel = new TextView(getContext());
expandedSmallLabel.setMaxLines(1);
expandedSmallLabel.setEllipsize(TruncateAt.END);
expandedSmallLabel.setDuplicateParentStateEnabled(true);
expandedSmallLabel.setIncludeFontPadding(false);
expandedSmallLabel.setGravity(Gravity.CENTER_VERTICAL);
// Set a default text size
expandedSmallLabel.setTextSize(defaultInactiveTextSize);
expandedLargeLabel = new TextView(getContext());
expandedLargeLabel.setMaxLines(1);
expandedLargeLabel.setEllipsize(TruncateAt.END);
expandedLargeLabel.setDuplicateParentStateEnabled(true);
expandedLargeLabel.setVisibility(INVISIBLE);
expandedLargeLabel.setIncludeFontPadding(false);
expandedLargeLabel.setGravity(Gravity.CENTER_VERTICAL);
// Set a default text size
expandedLargeLabel.setTextSize(defaultActiveTextSize);
expandedLabelGroup.addView(expandedSmallLabel);
expandedLabelGroup.addView(expandedLargeLabel);
}
private void addDefaultExpandedLabelGroupViews() {
LinearLayout.LayoutParams expandedLabelGroupLp = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
expandedLabelGroupLp.gravity = Gravity.CENTER;
innerContentContainer.addView(expandedLabelGroup, expandedLabelGroupLp);
setExpandedLabelGroupMargins();
}
private void updateItemIconGravity() {
int leftMargin = 0;
int rightMargin = 0;
int topMargin = 0;
int bottomMargin = 0;
int sidePadding = 0;
badgeFixedEdge = BadgeDrawable.BADGE_FIXED_EDGE_START;
int verticalLabelGroupVisibility = VISIBLE;
int horizontalLabelGroupVisibility = GONE;
currentLabelGroup = labelGroup;
if (itemIconGravity == ITEM_ICON_GRAVITY_START) {
if (expandedLabelGroup.getParent() == null) {
addDefaultExpandedLabelGroupViews();
}
leftMargin = itemActiveIndicatorExpandedPadding.left;
rightMargin = itemActiveIndicatorExpandedPadding.right;
topMargin = itemActiveIndicatorExpandedPadding.top;
bottomMargin = itemActiveIndicatorExpandedPadding.bottom;
badgeFixedEdge = BadgeDrawable.BADGE_FIXED_EDGE_END;
sidePadding = activeIndicatorExpandedMarginHorizontal;
verticalLabelGroupVisibility = GONE;
horizontalLabelGroupVisibility = VISIBLE;
currentLabelGroup = expandedLabelGroup;
}
labelGroup.setVisibility(verticalLabelGroupVisibility);
expandedLabelGroup.setVisibility(horizontalLabelGroupVisibility);
FrameLayout.LayoutParams contentContainerLp = (LayoutParams) contentContainer.getLayoutParams();
contentContainerLp.gravity = itemGravity;
FrameLayout.LayoutParams innerContentLp =
(LayoutParams) innerContentContainer.getLayoutParams();
innerContentLp.leftMargin = leftMargin;
innerContentLp.rightMargin = rightMargin;
innerContentLp.topMargin = topMargin;
innerContentLp.bottomMargin = bottomMargin;
setPadding(sidePadding, 0, sidePadding, 0);
updateActiveIndicatorLayoutParams(getWidth());
}
public void setItemIconGravity(@ItemIconGravity int iconGravity) {
if (itemIconGravity != iconGravity) {
itemIconGravity = iconGravity;
updateItemIconGravity();
refreshItemBackground();
}
}
@Override
public void setExpanded(boolean expanded) {
this.expanded = expanded;
updateVisibility();
}
@Override
public boolean isExpanded() {
return this.expanded;
}
@Override
public void setOnlyShowWhenExpanded(boolean onlyShowWhenExpanded) {
this.onlyShowWhenExpanded = onlyShowWhenExpanded;
updateVisibility();
}
@Override
public boolean isOnlyVisibleWhenExpanded() {
return this.onlyShowWhenExpanded;
}
@Override
@Nullable
public MenuItemImpl getItemData() {
return itemData;
}
@Override
public void setTitle(@Nullable CharSequence title) {
smallLabel.setText(title);
largeLabel.setText(title);
expandedSmallLabel.setText(title);
expandedLargeLabel.setText(title);
if (itemData == null || TextUtils.isEmpty(itemData.getContentDescription())) {
setContentDescription(title);
}
CharSequence tooltipText =
itemData == null || TextUtils.isEmpty(itemData.getTooltipText())
? title
: itemData.getTooltipText();
setItemTooltipText(tooltipText);
}
@Override
public void setOnLongClickListener(@Nullable OnLongClickListener listener) {
if (settingTooltipCompatLongClickListener) {
super.setOnLongClickListener(listener);
return;
}
customOnLongClickListener = listener;
super.setOnLongClickListener(listener);
updateTooltipText();
}
private void setItemTooltipText(@Nullable CharSequence tooltipText) {
this.tooltipText = tooltipText;
updateTooltipText();
}
private void updateTooltipText() {
// Avoid calling tooltip for L and M devices because long pressing twice may freeze devices.
if (VERSION.SDK_INT <= VERSION_CODES.M) {
return;
}
if (VERSION.SDK_INT >= VERSION_CODES.O) {
setTooltipText(tooltipText);
} else if (customOnLongClickListener == null) {
settingTooltipCompatLongClickListener = true;
try {
TooltipCompat.setTooltipText(this, tooltipText);
} finally {
settingTooltipCompatLongClickListener = false;
}
}
}
@Override
public void setCheckable(boolean checkable) {
refreshDrawableState();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// Update the width of the active indicator to fit within the bounds of its parent. This is
// needed when there is not enough width to accommodate the desired width of the indicator. Post
// this update in order to wait for parent layout changes to actually take effect before
// setting the new width.
final int width = w;
post(
new Runnable() {
@Override
public void run() {
updateActiveIndicatorLayoutParams(width);
}
});
}
private void updateActiveIndicatorTransform() {
if (isActiveIndicatorResizeableAndUnlabeled()) {
activeIndicatorTransform = ACTIVE_INDICATOR_UNLABELED_TRANSFORM;
} else {
activeIndicatorTransform = ACTIVE_INDICATOR_LABELED_TRANSFORM;
}
}
/**
* Update the active indicator for a given 0-1 value.
*
* @param progress 0 when the indicator should communicate an unselected state (typically gone), 1
* when the indicator should communicate a selected state (typically showing at its full width
* and height).
* @param target The final value towards which progress is animating. This can be used to
* determine if the indicator is being unselected or selected.
*/
private void setActiveIndicatorProgress(
@FloatRange(from = 0F, to = 1F) float progress, float target) {
activeIndicatorTransform.updateForProgress(progress, target, activeIndicatorView);
activeIndicatorProgress = progress;
}
/** If the active indicator is enabled, animate from it's current state to it's new state. */
private void maybeAnimateActiveIndicatorToProgress(
@FloatRange(from = 0F, to = 1F) final float newProgress) {
// If the active indicator is disabled or this view is in the process of being initialized,
// jump the active indicator to it's final state.
if (!activeIndicatorEnabled || !initialized || !isAttachedToWindow()) {
setActiveIndicatorProgress(newProgress, newProgress);
return;
}
if (activeIndicatorAnimator != null) {
activeIndicatorAnimator.cancel();
activeIndicatorAnimator = null;
}
activeIndicatorAnimator = ValueAnimator.ofFloat(activeIndicatorProgress, newProgress);
activeIndicatorAnimator.addUpdateListener(
new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float progress = (float) animation.getAnimatedValue();
setActiveIndicatorProgress(progress, newProgress);
}
});
activeIndicatorAnimator.setInterpolator(
MotionUtils.resolveThemeInterpolator(
getContext(),
R.attr.motionEasingEmphasizedInterpolator,
AnimationUtils.FAST_OUT_SLOW_IN_INTERPOLATOR));
activeIndicatorAnimator.setDuration(
MotionUtils.resolveThemeDuration(
getContext(),
R.attr.motionDurationLong2,
getResources().getInteger(R.integer.material_motion_duration_long_1)));
activeIndicatorAnimator.start();
}
/**
* Refresh the state of this item if it has been initialized.
*
* <p>This is useful if parameters calculated based on this item's checked state (label
* visibility, indicator state, icon position) have changed and should be recalculated.
*/
private void refreshChecked() {
if (itemData != null) {
setChecked(itemData.isChecked());
}
}
private void setLayoutConfigurationIconAndLabel(
View visibleLabel, View invisibleLabel, float scaleFactor, float topMarginShift) {
setViewMarginAndGravity(
contentContainer,
itemIconGravity == ITEM_ICON_GRAVITY_TOP ? (int) (itemPaddingTop + topMarginShift) : 0,
0,
itemGravity);
setViewMarginAndGravity(
innerContentContainer,
itemIconGravity == ITEM_ICON_GRAVITY_TOP ? 0 : itemActiveIndicatorExpandedPadding.top,
itemIconGravity == ITEM_ICON_GRAVITY_TOP ? 0 : itemActiveIndicatorExpandedPadding.bottom,
itemIconGravity == ITEM_ICON_GRAVITY_TOP
? Gravity.CENTER
: Gravity.START | Gravity.CENTER_VERTICAL);
updateViewPaddingBottom(labelGroup, itemPaddingBottom);
currentLabelGroup.setVisibility(VISIBLE);
setViewScaleValues(visibleLabel, 1f, 1f, VISIBLE);
setViewScaleValues(invisibleLabel, scaleFactor, scaleFactor, INVISIBLE);
}
private void setLayoutConfigurationIconOnly() {
setViewMarginAndGravity(contentContainer, itemPaddingTop, itemPaddingTop,
itemIconGravity == ITEM_ICON_GRAVITY_TOP ? Gravity.CENTER : itemGravity);
setViewMarginAndGravity(innerContentContainer, 0, 0, Gravity.CENTER);
updateViewPaddingBottom(labelGroup, 0);
currentLabelGroup.setVisibility(GONE);
}
private void setLabelPivots(TextView label) {
label.setPivotX((int) (label.getWidth() / 2));
label.setPivotY(label.getBaseline());
}
@Override
public void setChecked(boolean checked) {
setLabelPivots(largeLabel);
setLabelPivots(smallLabel);
setLabelPivots(expandedLargeLabel);
setLabelPivots(expandedSmallLabel);
float newIndicatorProgress = checked ? 1F : 0F;
maybeAnimateActiveIndicatorToProgress(newIndicatorProgress);
View selectedLabel = largeLabel;
View unselectedLabel = smallLabel;
float shiftAmount = this.shiftAmountY;
float scaleUpFactor = this.scaleUpFactor;
float scaleDownFactor = this.scaleDownFactor;
if (itemIconGravity == ITEM_ICON_GRAVITY_START) {
selectedLabel = expandedLargeLabel;
unselectedLabel = expandedSmallLabel;
shiftAmount = expandedLabelShiftAmountY;
scaleUpFactor = expandedLabelScaleUpFactor;
scaleDownFactor = expandedLabelScaleDownFactor;
}
switch (labelVisibilityMode) {
case NavigationBarView.LABEL_VISIBILITY_AUTO:
if (isShifting) {
if (checked) {
setLayoutConfigurationIconAndLabel(selectedLabel, unselectedLabel, scaleUpFactor, 0);
} else {
setLayoutConfigurationIconOnly();
}
} else {
if (checked) {
setLayoutConfigurationIconAndLabel(
selectedLabel, unselectedLabel, scaleUpFactor, shiftAmount);
} else {
setLayoutConfigurationIconAndLabel(unselectedLabel, selectedLabel, scaleDownFactor, 0);
}
}
break;
case NavigationBarView.LABEL_VISIBILITY_SELECTED:
if (checked) {
setLayoutConfigurationIconAndLabel(selectedLabel, unselectedLabel, scaleUpFactor, 0);
} else {
// Show icon only
setLayoutConfigurationIconOnly();
}
break;
case NavigationBarView.LABEL_VISIBILITY_LABELED:
if (checked) {
setLayoutConfigurationIconAndLabel(
selectedLabel, unselectedLabel, scaleUpFactor, shiftAmount);
} else {
setLayoutConfigurationIconAndLabel(unselectedLabel, selectedLabel, scaleDownFactor, 0);
}
break;
case NavigationBarView.LABEL_VISIBILITY_UNLABELED:
setLayoutConfigurationIconOnly();
break;
default:
break;
}
refreshDrawableState();
// Set the item as selected to send an AccessibilityEvent.TYPE_VIEW_SELECTED from View, so that
// the item is read out as selected.
setSelected(checked);
}
@Override
public void onInitializeAccessibilityNodeInfo(@NonNull AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
if (badgeDrawable != null && badgeDrawable.isVisible()) {
CharSequence customContentDescription = itemData.getTitle();
if (!TextUtils.isEmpty(itemData.getContentDescription())) {
customContentDescription = itemData.getContentDescription();
}
info.setContentDescription(
customContentDescription + ", " + badgeDrawable.getContentDescription());
}
AccessibilityNodeInfoCompat infoCompat = AccessibilityNodeInfoCompat.wrap(info);
infoCompat.setCollectionItemInfo(
CollectionItemInfoCompat.obtain(
/* rowIndex= */ 0,
/* rowSpan= */ 1,
/* columnIndex= */ getItemVisiblePosition(),
/* columnSpan= */ 1,
/* heading= */ false,
/* selected= */ isSelected()));
if (isSelected()) {
infoCompat.setClickable(false);
infoCompat.removeAction(AccessibilityActionCompat.ACTION_CLICK);
}
infoCompat.setRoleDescription(getResources().getString(R.string.item_view_role_description));
}
/**
* Iterate through all the preceding bottom navigating items to determine this item's visible
* position.
*
* @return This item's visible position in a bottom navigation.
*/
private int getItemVisiblePosition() {
ViewGroup parent = (ViewGroup) getParent();
int index = parent.indexOfChild(this);
int visiblePosition = 0;
for (int i = 0; i < index; i++) {
View child = parent.getChildAt(i);
if (child instanceof NavigationBarItemView && child.getVisibility() == View.VISIBLE) {
visiblePosition++;
}
}
return visiblePosition;
}
private static void setViewMarginAndGravity(
@NonNull View view, int topMargin, int bottomMargin, int gravity) {
LayoutParams viewParams = (LayoutParams) view.getLayoutParams();
viewParams.topMargin = topMargin;
viewParams.bottomMargin = bottomMargin;
viewParams.gravity = gravity;
view.setLayoutParams(viewParams);
}
private static void setViewScaleValues(
@NonNull View view, float scaleX, float scaleY, int visibility) {
view.setScaleX(scaleX);
view.setScaleY(scaleY);
view.setVisibility(visibility);
}
private static void updateViewPaddingBottom(@NonNull View view, int paddingBottom) {
view.setPadding(
view.getPaddingLeft(), view.getPaddingTop(), view.getPaddingRight(), paddingBottom);
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
smallLabel.setEnabled(enabled);
largeLabel.setEnabled(enabled);
expandedSmallLabel.setEnabled(enabled);
expandedLargeLabel.setEnabled(enabled);
icon.setEnabled(enabled);
}
@Override
@NonNull
public int[] onCreateDrawableState(final int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
if (itemData != null && itemData.isCheckable() && itemData.isChecked()) {
mergeDrawableStates(drawableState, CHECKED_STATE_SET);
}
return drawableState;
}
@Override
public void setShortcut(boolean showShortcut, char shortcutKey) {}
@Override
public void setIcon(@Nullable Drawable iconDrawable) {
if (iconDrawable == originalIconDrawable) {
return;
}
// Save the original icon to check if it has changed in future calls of this method.
originalIconDrawable = iconDrawable;
if (iconDrawable != null) {
Drawable.ConstantState state = iconDrawable.getConstantState();
iconDrawable =
DrawableCompat.wrap(state == null ? iconDrawable : state.newDrawable()).mutate();
wrappedIconDrawable = iconDrawable;
if (iconTint != null) {
wrappedIconDrawable.setTintList(iconTint);
}
}
this.icon.setImageDrawable(iconDrawable);
}
@Override
public boolean prefersCondensedTitle() {
return false;
}
@Override
public boolean showsIcon() {
return true;
}
public void setIconTintList(@Nullable ColorStateList tint) {
iconTint = tint;
if (itemData != null && wrappedIconDrawable != null) {
wrappedIconDrawable.setTintList(iconTint);
wrappedIconDrawable.invalidateSelf();
}
}
public void setIconSize(int iconSize) {
LinearLayout.LayoutParams iconParams = (LinearLayout.LayoutParams) icon.getLayoutParams();
iconParams.width = iconSize;
iconParams.height = iconSize;
icon.setLayoutParams(iconParams);
// Reset expanded label group margins, in case the icon width is now 0
setExpandedLabelGroupMargins();
}
private void setExpandedLabelGroupMargins() {
int margin = icon.getLayoutParams().width > 0 ? iconLabelHorizontalSpacing : 0;
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) expandedLabelGroup.getLayoutParams();
if (lp != null) {
lp.rightMargin = getLayoutDirection() == LAYOUT_DIRECTION_RTL ? margin : 0;
lp.leftMargin = getLayoutDirection() == LAYOUT_DIRECTION_RTL ? 0 : margin;
}
}
// TODO(b/338647654): We can remove this once navigation rail is updated
public void setMeasureBottomPaddingFromLabelBaseline(boolean measurePaddingFromBaseline) {
this.measurePaddingFromBaseline = measurePaddingFromBaseline;
labelGroup.setMeasurePaddingFromBaseline(measurePaddingFromBaseline);
smallLabel.setIncludeFontPadding(measurePaddingFromBaseline);
largeLabel.setIncludeFontPadding(measurePaddingFromBaseline);
expandedLabelGroup.setMeasurePaddingFromBaseline(measurePaddingFromBaseline);
expandedSmallLabel.setIncludeFontPadding(measurePaddingFromBaseline);
expandedLargeLabel.setIncludeFontPadding(measurePaddingFromBaseline);
requestLayout();
}
public void setLabelFontScalingEnabled(boolean scaleLabelSizeWithFont) {
this.scaleLabelSizeWithFont = scaleLabelSizeWithFont;
setTextAppearanceActive(textAppearanceActive);
setTextAppearanceInactive(textAppearanceInactive);
setHorizontalTextAppearanceActive(horizontalTextAppearanceActive);
setHorizontalTextAppearanceInactive(horizontalTextAppearanceInactive);
}
private void setTextAppearanceForLabel(TextView label, int textAppearance) {
if (scaleLabelSizeWithFont) {
TextViewCompat.setTextAppearance(label, textAppearance);
} else {
setTextAppearanceWithoutFontScaling(label, textAppearance);
}
}
private void updateInactiveLabelTextAppearance(
@Nullable TextView smallLabel, @StyleRes int textAppearanceInactive) {
if (smallLabel == null) {
return;
}
setTextAppearanceForLabel(smallLabel, textAppearanceInactive);
calculateTextScaleFactors();
smallLabel.setMinimumHeight(
MaterialResources.getUnscaledLineHeight(
smallLabel.getContext(), textAppearanceInactive, 0));
// Set the text color if the user has set it, since it takes precedence
// over a color set in the text appearance.
if (textColor != null) {
smallLabel.setTextColor(textColor);
}
}
private void updateActiveLabelTextAppearance(
@Nullable TextView largeLabel, @StyleRes int textAppearanceActive) {
if (largeLabel == null) {
return;
}
setTextAppearanceForLabel(largeLabel, textAppearanceActive);
calculateTextScaleFactors();
largeLabel.setMinimumHeight(
MaterialResources.getUnscaledLineHeight(
largeLabel.getContext(), textAppearanceActive, 0));
// Set the text color if the user has set it, since it takes precedence
// over a color set in the text appearance.
if (textColor != null) {
largeLabel.setTextColor(textColor);
}
updateActiveLabelBoldness();
}
public void setTextAppearanceInactive(@StyleRes int inactiveTextAppearance) {
this.textAppearanceInactive = inactiveTextAppearance;
updateInactiveLabelTextAppearance(smallLabel, textAppearanceInactive);
}
public void setTextAppearanceActive(@StyleRes int activeTextAppearance) {
this.textAppearanceActive = activeTextAppearance;
updateActiveLabelTextAppearance(largeLabel, textAppearanceActive);
}
public void setHorizontalTextAppearanceInactive(@StyleRes int inactiveTextAppearance) {
horizontalTextAppearanceInactive = inactiveTextAppearance;
updateInactiveLabelTextAppearance(
expandedSmallLabel,
horizontalTextAppearanceInactive != 0
? horizontalTextAppearanceInactive : textAppearanceInactive);
}
public void setHorizontalTextAppearanceActive(@StyleRes int activeTextAppearance) {
horizontalTextAppearanceActive = activeTextAppearance;
updateActiveLabelTextAppearance(
expandedLargeLabel,
horizontalTextAppearanceActive != 0
? horizontalTextAppearanceActive : textAppearanceActive);
}
public void setTextAppearanceActiveBoldEnabled(boolean isBold) {
boldText = isBold;
setTextAppearanceActive(textAppearanceActive);
setHorizontalTextAppearanceActive(horizontalTextAppearanceActive);
updateActiveLabelBoldness();
}
private void updateActiveLabelBoldness() {
// TODO(b/246765947): Use component tokens to control font weight
largeLabel.setTypeface(largeLabel.getTypeface(), boldText ? Typeface.BOLD : Typeface.NORMAL);
expandedLargeLabel.setTypeface(
expandedLargeLabel.getTypeface(), boldText ? Typeface.BOLD : Typeface.NORMAL);
}
/**
* Remove font scaling if the text size is in scaled pixels.
*
* <p>Labels are instead made accessible by showing a scaled tooltip on long press of a
* destination. If the given {@code textAppearance} is 0 or does not have a textSize, this method
* will not remove the existing scaling from the {@code textView}.
*/
private static void setTextAppearanceWithoutFontScaling(
TextView textView, @StyleRes int textAppearance) {
TextViewCompat.setTextAppearance(textView, textAppearance);
int unscaledSize =
MaterialResources.getUnscaledTextSize(textView.getContext(), textAppearance, 0);
if (unscaledSize != 0) {
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, unscaledSize);
}
}
public void setLabelMaxLines(int labelMaxLines) {
smallLabel.setMaxLines(labelMaxLines);
largeLabel.setMaxLines(labelMaxLines);
expandedSmallLabel.setMaxLines(labelMaxLines);
expandedLargeLabel.setMaxLines(labelMaxLines);
// Due to b/316260445 that was fixed in V+, text with ellipses may be cut off when centered
// due to letter spacing being miscalculated for the ellipses character. We only center the text
// in the following scenarios:
// 1. API level is greater than 34, OR
// 2. The text is not cut off by an ellipses