-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathTabLayout.java
3614 lines (3235 loc) · 129 KB
/
TabLayout.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.tabs;
import com.google.android.material.R;
import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP;
import static androidx.viewpager.widget.ViewPager.SCROLL_STATE_DRAGGING;
import static androidx.viewpager.widget.ViewPager.SCROLL_STATE_IDLE;
import static androidx.viewpager.widget.ViewPager.SCROLL_STATE_SETTLING;
import static com.google.android.material.animation.AnimationUtils.FAST_OUT_SLOW_IN_INTERPOLATOR;
import static com.google.android.material.theme.overlay.MaterialThemeOverlay.wrap;
import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.RippleDrawable;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.appcompat.widget.TooltipCompat;
import android.text.Layout;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.BoolRes;
import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.annotation.Dimension;
import androidx.annotation.DrawableRes;
import androidx.annotation.IntDef;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RestrictTo;
import androidx.annotation.StringRes;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.core.util.Pools;
import androidx.core.view.PointerIconCompat;
import androidx.core.view.ViewCompat;
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat;
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat;
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat.CollectionInfoCompat;
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat.CollectionItemInfoCompat;
import androidx.core.widget.TextViewCompat;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.badge.BadgeDrawable;
import com.google.android.material.badge.BadgeUtils;
import com.google.android.material.drawable.DrawableUtils;
import com.google.android.material.internal.ThemeEnforcement;
import com.google.android.material.internal.ViewUtils;
import com.google.android.material.motion.MotionUtils;
import com.google.android.material.resources.MaterialResources;
import com.google.android.material.ripple.RippleUtils;
import com.google.android.material.shape.MaterialShapeDrawable;
import com.google.android.material.shape.MaterialShapeUtils;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
/**
* TabLayout provides a horizontal layout to display tabs.
*
* <p>Population of the tabs to display is done through {@link Tab} instances. You create tabs via
* {@link #newTab()}. From there you can change the tab's label or icon via {@link Tab#setText(int)}
* and {@link Tab#setIcon(int)} respectively. To display the tab, you need to add it to the layout
* via one of the {@link #addTab(Tab)} methods. For example:
*
* <pre>
* TabLayout tabLayout = ...;
* tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
* tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
* tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
* </pre>
*
* You should add a listener via {@link #addOnTabSelectedListener(OnTabSelectedListener)} to be
* notified when any tab's selection state has been changed.
*
* <p>You can also add items to TabLayout in your layout through the use of {@link TabItem}. An
* example usage is like so:
*
* <pre>
* <com.google.android.material.tabs.TabLayout
* android:layout_height="wrap_content"
* android:layout_width="match_parent">
*
* <com.google.android.material.tabs.TabItem
* android:text="@string/tab_text"/>
*
* <com.google.android.material.tabs.TabItem
* android:icon="@drawable/ic_android"/>
*
* </com.google.android.material.tabs.TabLayout>
* </pre>
*
* <h3>ViewPager integration</h3>
*
* <p>If you're using a {@link androidx.viewpager.widget.ViewPager} together with this layout, you
* can call {@link #setupWithViewPager(ViewPager)} to link the two together. This layout will be
* automatically populated from the {@link PagerAdapter}'s page titles.
*
* <p>This view also supports being used as part of a ViewPager's decor, and can be added directly
* to the ViewPager in a layout resource file like so:
*
* <pre>
* <androidx.viewpager.widget.ViewPager
* android:layout_width="match_parent"
* android:layout_height="match_parent">
*
* <com.google.android.material.tabs.TabLayout
* android:layout_width="match_parent"
* android:layout_height="wrap_content"
* android:layout_gravity="top" />
*
* </androidx.viewpager.widget.ViewPager>
* </pre>
*
* <p>For more information, see the <a
* href="https://github.com/material-components/material-components-android/blob/master/docs/components/Tabs.md">component
* developer guidance</a> and <a href="https://material.io/components/tabs/overview">design
* guidelines</a>.
*
* @see <a href="http://www.google.com/design/spec/components/tabs.html">Tabs</a>
* @attr ref com.google.android.material.R.styleable#TabLayout_tabPadding
* @attr ref com.google.android.material.R.styleable#TabLayout_tabPaddingStart
* @attr ref com.google.android.material.R.styleable#TabLayout_tabPaddingTop
* @attr ref com.google.android.material.R.styleable#TabLayout_tabPaddingEnd
* @attr ref com.google.android.material.R.styleable#TabLayout_tabPaddingBottom
* @attr ref com.google.android.material.R.styleable#TabLayout_tabContentStart
* @attr ref com.google.android.material.R.styleable#TabLayout_tabBackground
* @attr ref com.google.android.material.R.styleable#TabLayout_tabMinWidth
* @attr ref com.google.android.material.R.styleable#TabLayout_tabMaxWidth
* @attr ref com.google.android.material.R.styleable#TabLayout_tabTextAppearance
*/
@ViewPager.DecorView
public class TabLayout extends HorizontalScrollView {
private static final int DEF_STYLE_RES = R.style.Widget_Design_TabLayout;
@Dimension(unit = Dimension.DP)
private static final int DEFAULT_HEIGHT_WITH_TEXT_ICON = 72;
@Dimension(unit = Dimension.DP)
static final int DEFAULT_GAP_TEXT_ICON = 8;
@Dimension(unit = Dimension.DP)
private static final int DEFAULT_HEIGHT = 48;
@Dimension(unit = Dimension.DP)
private static final int TAB_MIN_WIDTH_MARGIN = 56;
@Dimension(unit = Dimension.DP)
static final int FIXED_WRAP_GUTTER_MIN = 16;
private static final int INVALID_WIDTH = -1;
private static final int ANIMATION_DURATION = 300;
private static final int SELECTED_INDICATOR_HEIGHT_DEFAULT = -1;
private static final Pools.Pool<Tab> tabPool = new Pools.SynchronizedPool<>(16);
private static final String LOG_TAG = "TabLayout";
/**
* Scrollable tabs display a subset of tabs at any given moment, and can contain longer tab labels
* and a larger number of tabs. They are best used for browsing contexts in touch interfaces when
* users don't need to directly compare the tab labels.
*
* @see #setTabMode(int)
* @see #getTabMode()
*/
public static final int MODE_SCROLLABLE = 0;
/**
* Fixed tabs display all tabs concurrently and are best used with content that benefits from
* quick pivots between tabs. The maximum number of tabs is limited by the view's width. Fixed
* tabs have equal width, based on the widest tab label.
*
* @see #setTabMode(int)
* @see #getTabMode()
*/
public static final int MODE_FIXED = 1;
/**
* Auto-sizing tabs behave like MODE_FIXED with GRAVITY_CENTER while the tabs fit within the
* TabLayout's content width. Fixed tabs have equal width, based on the widest tab label. Once the
* tabs outgrow the view's width, auto-sizing tabs behave like MODE_SCROLLABLE, allowing for a
* dynamic number of tabs without requiring additional layout logic.
*
* @see #setTabMode(int)
* @see #getTabMode()
*/
public static final int MODE_AUTO = 2;
/** @hide */
@RestrictTo(LIBRARY_GROUP)
@IntDef(value = {MODE_SCROLLABLE, MODE_FIXED, MODE_AUTO})
@Retention(RetentionPolicy.SOURCE)
public @interface Mode {}
/**
* If a tab is instantiated with {@link Tab#setText(CharSequence)}, and this mode is set, the text
* will be saved and utilized for the content description, but no visible labels will be created.
*
* @see Tab#setTabLabelVisibility(int)
*/
public static final int TAB_LABEL_VISIBILITY_UNLABELED = 0;
/**
* This mode is set by default. If a tab is instantiated with {@link Tab#setText(CharSequence)}, a
* visible label will be created.
*
* @see Tab#setTabLabelVisibility(int)
*/
public static final int TAB_LABEL_VISIBILITY_LABELED = 1;
/** @hide */
@IntDef(value = {TAB_LABEL_VISIBILITY_UNLABELED, TAB_LABEL_VISIBILITY_LABELED})
public @interface LabelVisibility {}
/**
* Gravity used to fill the {@link TabLayout} as much as possible. This option only takes effect
* when used with {@link #MODE_FIXED} on non-landscape screens less than 600dp wide.
*
* @see #setTabGravity(int)
* @see #getTabGravity()
*/
public static final int GRAVITY_FILL = 0;
/**
* Gravity used to lay out the tabs in the center of the {@link TabLayout}.
*
* @see #setTabGravity(int)
* @see #getTabGravity()
*/
public static final int GRAVITY_CENTER = 1;
/**
* Gravity used to lay out the tabs aligned to the start of the {@link TabLayout}.
*
* @see #setTabGravity(int)
* @see #getTabGravity()
*/
public static final int GRAVITY_START = 1 << 1;
/** @hide */
@RestrictTo(LIBRARY_GROUP)
@IntDef(
flag = true,
value = {GRAVITY_FILL, GRAVITY_CENTER, GRAVITY_START})
@Retention(RetentionPolicy.SOURCE)
public @interface TabGravity {}
// indicatorPosition keeps track of where the indicator is.
int indicatorPosition = -1;
/**
* Indicator gravity used to align the tab selection indicator to the bottom of the {@link
* TabLayout}. This will only take effect if the indicator height is set via the custom indicator
* drawable's intrinsic height (preferred), via the {@code tabIndicatorHeight} attribute
* (deprecated), or via {@link #setSelectedTabIndicatorHeight(int)} (deprecated). Otherwise, the
* indicator will not be shown. This is the default value.
*
* @see #setSelectedTabIndicatorGravity(int)
* @see #getTabIndicatorGravity()
* @attr ref com.google.android.material.R.styleable#TabLayout_tabIndicatorGravity
*/
public static final int INDICATOR_GRAVITY_BOTTOM = 0;
/**
* Indicator gravity used to align the tab selection indicator to the center of the {@link
* TabLayout}. This will only take effect if the indicator height is set via the custom indicator
* drawable's intrinsic height (preferred), via the {@code tabIndicatorHeight} attribute
* (deprecated), or via {@link #setSelectedTabIndicatorHeight(int)} (deprecated). Otherwise, the
* indicator will not be shown.
*
* @see #setSelectedTabIndicatorGravity(int)
* @see #getTabIndicatorGravity()
* @attr ref com.google.android.material.R.styleable#TabLayout_tabIndicatorGravity
*/
public static final int INDICATOR_GRAVITY_CENTER = 1;
/**
* Indicator gravity used to align the tab selection indicator to the top of the {@link
* TabLayout}. This will only take effect if the indicator height is set via the custom indicator
* drawable's intrinsic height (preferred), via the {@code tabIndicatorHeight} attribute
* (deprecated), or via {@link #setSelectedTabIndicatorHeight(int)} (deprecated). Otherwise, the
* indicator will not be shown.
*
* @see #setSelectedTabIndicatorGravity(int)
* @see #getTabIndicatorGravity()
* @attr ref com.google.android.material.R.styleable#TabLayout_tabIndicatorGravity
*/
public static final int INDICATOR_GRAVITY_TOP = 2;
/**
* Indicator gravity used to stretch the tab selection indicator across the entire height
* of the {@link TabLayout}. This will disregard {@code tabIndicatorHeight} and the
* indicator drawable's intrinsic height, if set.
*
* @see #setSelectedTabIndicatorGravity(int)
* @see #getTabIndicatorGravity()
* @attr ref com.google.android.material.R.styleable#TabLayout_tabIndicatorGravity
*/
public static final int INDICATOR_GRAVITY_STRETCH = 3;
/** @hide */
@RestrictTo(LIBRARY_GROUP)
@IntDef(
value = {
INDICATOR_GRAVITY_BOTTOM,
INDICATOR_GRAVITY_CENTER,
INDICATOR_GRAVITY_TOP,
INDICATOR_GRAVITY_STRETCH
})
@Retention(RetentionPolicy.SOURCE)
public @interface TabIndicatorGravity {}
/**
* Indicator animation mode used to translate the selected tab indicator between two tabs using a
* linear motion.
*
* <p>The left and right side of the selection indicator translate in step over the duration of
* the animation. The only exception to this is when the indicator needs to change size to fit the
* width of its new destination tab's label.
*
* @see #setTabIndicatorAnimationMode(int)
* @see #getTabIndicatorAnimationMode()
* @attr ref com.google.android.material.R.styleable#TabLayout_tabIndicatorAnimationMode
*/
public static final int INDICATOR_ANIMATION_MODE_LINEAR = 0;
/**
* Indicator animation mode used to translate the selected tab indicator by growing and then
* shrinking the indicator, making the indicator look like it is stretching while translating
* between destinations.
*
* <p>The left and right side of the selection indicator translate out of step - with the right
* decelerating and the left accelerating (when moving right). This difference in velocity between
* the sides of the indicator, over the duration of the animation, make the indicator look like it
* grows and then shrinks back down to fit it's new destination's width.
*
* @see #setTabIndicatorAnimationMode(int)
* @see #getTabIndicatorAnimationMode()
* @attr ref com.google.android.material.R.styleable#TabLayout_tabIndicatorAnimationMode
*/
public static final int INDICATOR_ANIMATION_MODE_ELASTIC = 1;
/**
* Indicator animation mode used to switch the selected tab indicator from one tab to another
* by sequentially fading it out from the current destination and in at its new destination.
*
* @see #setTabIndicatorAnimationMode(int)
* @see #getTabIndicatorAnimationMode()
* @attr ref com.google.android.material.R.styleable#TabLayout_tabIndicatorAnimationMode
*/
public static final int INDICATOR_ANIMATION_MODE_FADE = 2;
/** @hide */
@RestrictTo(LIBRARY_GROUP)
@IntDef(value = {
INDICATOR_ANIMATION_MODE_LINEAR,
INDICATOR_ANIMATION_MODE_ELASTIC,
INDICATOR_ANIMATION_MODE_FADE
})
@Retention(RetentionPolicy.SOURCE)
public @interface TabIndicatorAnimationMode {}
/** Callback interface invoked when a tab's selection state changes. */
public interface OnTabSelectedListener extends BaseOnTabSelectedListener<Tab> {}
/**
* Callback interface invoked when a tab's selection state changes.
*
* @deprecated Use {@link OnTabSelectedListener} instead.
*/
@Deprecated
public interface BaseOnTabSelectedListener<T extends Tab> {
/**
* Called when a tab enters the selected state.
*
* @param tab The tab that was selected
*/
public void onTabSelected(T tab);
/**
* Called when a tab exits the selected state.
*
* @param tab The tab that was unselected
*/
public void onTabUnselected(T tab);
/**
* Called when a tab that is already selected is chosen again by the user. Some applications may
* use this action to return to the top level of a category.
*
* @param tab The tab that was reselected.
*/
public void onTabReselected(T tab);
}
private final ArrayList<Tab> tabs = new ArrayList<>();
@Nullable private Tab selectedTab;
@NonNull final SlidingTabIndicator slidingTabIndicator;
int tabPaddingStart;
int tabPaddingTop;
int tabPaddingEnd;
int tabPaddingBottom;
private final int defaultTabTextAppearance;
private final int tabTextAppearance;
private int selectedTabTextAppearance = -1;
ColorStateList tabTextColors;
ColorStateList tabIconTint;
ColorStateList tabRippleColorStateList;
@NonNull Drawable tabSelectedIndicator;
private int tabSelectedIndicatorColor = Color.TRANSPARENT;
android.graphics.PorterDuff.Mode tabIconTintMode;
float tabTextSize;
float selectedTabTextSize;
float tabTextMultiLineSize;
final int tabBackgroundResId;
int tabMaxWidth = Integer.MAX_VALUE;
private final int requestedTabMinWidth;
private final int requestedTabMaxWidth;
private final int scrollableTabMinWidth;
private int contentInsetStart;
@TabGravity int tabGravity;
int tabIndicatorAnimationDuration;
@TabIndicatorGravity int tabIndicatorGravity;
@Mode int mode;
boolean inlineLabel;
boolean tabIndicatorFullWidth;
int tabIndicatorHeight = SELECTED_INDICATOR_HEIGHT_DEFAULT;
@TabIndicatorAnimationMode int tabIndicatorAnimationMode;
boolean unboundedRipple;
private TabIndicatorInterpolator tabIndicatorInterpolator;
private final TimeInterpolator tabIndicatorTimeInterpolator;
@Nullable private BaseOnTabSelectedListener selectedListener;
private final ArrayList<BaseOnTabSelectedListener> selectedListeners = new ArrayList<>();
@Nullable private BaseOnTabSelectedListener currentVpSelectedListener;
private ValueAnimator scrollAnimator;
@Nullable ViewPager viewPager;
@Nullable private PagerAdapter pagerAdapter;
private DataSetObserver pagerAdapterObserver;
private TabLayoutOnPageChangeListener pageChangeListener;
private AdapterChangeListener adapterChangeListener;
private boolean setupViewPagerImplicitly;
private int viewPagerScrollState;
// Pool we use as a simple RecyclerBin
private final Pools.Pool<TabView> tabViewPool = new Pools.SimplePool<>(12);
public TabLayout(@NonNull Context context) {
this(context, null);
}
public TabLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, R.attr.tabStyle);
}
public TabLayout(@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();
// Disable the Scroll Bar
setHorizontalScrollBarEnabled(false);
// Add the TabStrip
slidingTabIndicator = new SlidingTabIndicator(context);
super.addView(
slidingTabIndicator,
0,
new HorizontalScrollView.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
TypedArray a =
ThemeEnforcement.obtainStyledAttributes(
context,
attrs,
R.styleable.TabLayout,
defStyleAttr,
DEF_STYLE_RES,
R.styleable.TabLayout_tabTextAppearance);
ColorStateList backgroundColorStateList =
DrawableUtils.getColorStateListOrNull(getBackground());
if (backgroundColorStateList != null) {
MaterialShapeDrawable materialShapeDrawable = new MaterialShapeDrawable();
materialShapeDrawable.setFillColor(backgroundColorStateList);
materialShapeDrawable.initializeElevationOverlay(context);
materialShapeDrawable.setElevation(getElevation());
setBackground(materialShapeDrawable);
}
setSelectedTabIndicator(
MaterialResources.getDrawable(context, a, R.styleable.TabLayout_tabIndicator));
setSelectedTabIndicatorColor(
a.getColor(R.styleable.TabLayout_tabIndicatorColor, Color.TRANSPARENT));
slidingTabIndicator.setSelectedIndicatorHeight(
a.getDimensionPixelSize(R.styleable.TabLayout_tabIndicatorHeight, -1));
setSelectedTabIndicatorGravity(
a.getInt(R.styleable.TabLayout_tabIndicatorGravity, INDICATOR_GRAVITY_BOTTOM));
setTabIndicatorAnimationMode(
a.getInt(R.styleable.TabLayout_tabIndicatorAnimationMode, INDICATOR_ANIMATION_MODE_LINEAR));
setTabIndicatorFullWidth(a.getBoolean(R.styleable.TabLayout_tabIndicatorFullWidth, true));
tabPaddingStart =
tabPaddingTop =
tabPaddingEnd =
tabPaddingBottom = a.getDimensionPixelSize(R.styleable.TabLayout_tabPadding, 0);
tabPaddingStart =
a.getDimensionPixelSize(R.styleable.TabLayout_tabPaddingStart, tabPaddingStart);
tabPaddingTop = a.getDimensionPixelSize(R.styleable.TabLayout_tabPaddingTop, tabPaddingTop);
tabPaddingEnd = a.getDimensionPixelSize(R.styleable.TabLayout_tabPaddingEnd, tabPaddingEnd);
tabPaddingBottom =
a.getDimensionPixelSize(R.styleable.TabLayout_tabPaddingBottom, tabPaddingBottom);
if (ThemeEnforcement.isMaterial3Theme(context)) {
defaultTabTextAppearance = R.attr.textAppearanceTitleSmall;
} else {
defaultTabTextAppearance = R.attr.textAppearanceButton;
}
tabTextAppearance =
a.getResourceId(R.styleable.TabLayout_tabTextAppearance, R.style.TextAppearance_Design_Tab);
// Text colors/sizes come from the text appearance first
final TypedArray ta =
context.obtainStyledAttributes(
tabTextAppearance, androidx.appcompat.R.styleable.TextAppearance);
try {
tabTextSize =
ta.getDimensionPixelSize(
androidx.appcompat.R.styleable.TextAppearance_android_textSize, 0);
tabTextColors =
MaterialResources.getColorStateList(
context,
ta,
androidx.appcompat.R.styleable.TextAppearance_android_textColor);
} finally {
ta.recycle();
}
if (a.hasValue(R.styleable.TabLayout_tabSelectedTextAppearance)) {
selectedTabTextAppearance =
a.getResourceId(R.styleable.TabLayout_tabSelectedTextAppearance, tabTextAppearance);
}
if (selectedTabTextAppearance != -1) {
// If there is a selected tab text appearance specified, we take the selected tab text size
// and selected color from it.
@SuppressLint("CustomViewStyleable")
final TypedArray selectedTabTA =
context.obtainStyledAttributes(
selectedTabTextAppearance, androidx.appcompat.R.styleable.TextAppearance);
try {
selectedTabTextSize =
selectedTabTA.getDimensionPixelSize(
androidx.appcompat.R.styleable.TextAppearance_android_textSize,
(int) tabTextSize);
ColorStateList selectedTabTextColor =
MaterialResources.getColorStateList(
context,
selectedTabTA,
androidx.appcompat.R.styleable.TextAppearance_android_textColor);
// Merge the selected tab color if it's set in the selected tab text appearance.
if (selectedTabTextColor != null) {
tabTextColors =
createColorStateList(
tabTextColors.getDefaultColor(),
selectedTabTextColor.getColorForState(
new int[] {android.R.attr.state_selected},
selectedTabTextColor.getDefaultColor()));
}
} finally {
selectedTabTA.recycle();
}
}
if (a.hasValue(R.styleable.TabLayout_tabTextColor)) {
// If we have an explicit text color set, use it instead
tabTextColors =
MaterialResources.getColorStateList(context, a, R.styleable.TabLayout_tabTextColor);
}
if (a.hasValue(R.styleable.TabLayout_tabSelectedTextColor)) {
// We have an explicit selected text color set, so we need to make merge it with the
// current colors. This is exposed so that developers can use theme attributes to set
// this (theme attrs in ColorStateLists are Lollipop+)
final int selected = a.getColor(R.styleable.TabLayout_tabSelectedTextColor, 0);
tabTextColors = createColorStateList(tabTextColors.getDefaultColor(), selected);
}
tabIconTint =
MaterialResources.getColorStateList(context, a, R.styleable.TabLayout_tabIconTint);
tabIconTintMode =
ViewUtils.parseTintMode(a.getInt(R.styleable.TabLayout_tabIconTintMode, -1), null);
tabRippleColorStateList =
MaterialResources.getColorStateList(context, a, R.styleable.TabLayout_tabRippleColor);
tabIndicatorAnimationDuration =
a.getInt(R.styleable.TabLayout_tabIndicatorAnimationDuration, ANIMATION_DURATION);
tabIndicatorTimeInterpolator =
MotionUtils.resolveThemeInterpolator(
context, R.attr.motionEasingEmphasizedInterpolator, FAST_OUT_SLOW_IN_INTERPOLATOR);
requestedTabMinWidth =
a.getDimensionPixelSize(R.styleable.TabLayout_tabMinWidth, INVALID_WIDTH);
requestedTabMaxWidth =
a.getDimensionPixelSize(R.styleable.TabLayout_tabMaxWidth, INVALID_WIDTH);
tabBackgroundResId = a.getResourceId(R.styleable.TabLayout_tabBackground, 0);
contentInsetStart = a.getDimensionPixelSize(R.styleable.TabLayout_tabContentStart, 0);
// noinspection WrongConstant
mode = a.getInt(R.styleable.TabLayout_tabMode, MODE_FIXED);
tabGravity = a.getInt(R.styleable.TabLayout_tabGravity, GRAVITY_FILL);
inlineLabel = a.getBoolean(R.styleable.TabLayout_tabInlineLabel, false);
unboundedRipple = a.getBoolean(R.styleable.TabLayout_tabUnboundedRipple, false);
a.recycle();
// TODO add attr for these
final Resources res = getResources();
tabTextMultiLineSize = res.getDimensionPixelSize(R.dimen.design_tab_text_size_2line);
scrollableTabMinWidth = res.getDimensionPixelSize(R.dimen.design_tab_scrollable_min_width);
// Now apply the tab mode and gravity
applyModeAndGravity();
}
/**
* Sets the tab indicator's color for the currently selected tab.
*
* <p>If the tab indicator color is not {@code Color.TRANSPARENT}, the indicator will be wrapped
* and tinted right before it is drawn by {@link SlidingTabIndicator#draw(Canvas)}. If you'd like
* the inherent color or the tinted color of a custom drawable to be used, make sure this color is
* set to {@code Color.TRANSPARENT} to avoid your color/tint being overridden.
*
* @param color color to use for the indicator
* @attr ref com.google.android.material.R.styleable#TabLayout_tabIndicatorColor
*/
public void setSelectedTabIndicatorColor(@ColorInt int color) {
this.tabSelectedIndicatorColor = color;
DrawableUtils.setTint(tabSelectedIndicator, tabSelectedIndicatorColor);
updateTabViews(false);
}
/**
* Sets the tab indicator's height for the currently selected tab.
*
* @deprecated If possible, set the intrinsic height directly on a custom indicator drawable
* passed to {@link #setSelectedTabIndicator(Drawable)}.
* @param height height to use for the indicator in pixels
* @attr ref com.google.android.material.R.styleable#TabLayout_tabIndicatorHeight
*/
@Deprecated
public void setSelectedTabIndicatorHeight(int height) {
tabIndicatorHeight = height;
slidingTabIndicator.setSelectedIndicatorHeight(height);
}
/**
* Set the scroll position of the {@link TabLayout}.
*
* @param position Position of the tab to scroll.
* @param positionOffset Value from [0, 1) indicating the offset from {@code position}.
* @param updateSelectedTabView Whether to draw the tab at the specified position + positionOffset
* as selected.
* <p>Note that calling the method with {@code updateSelectedTabView = true}
* <em>does not</em> select a tab at the specified position, but only <em>draws it
* as selected</em>. This can be useful for when the TabLayout behavior needs to be linked to
* another view, such as {@link androidx.viewpager.widget.ViewPager}.
* @see #setScrollPosition(int, float, boolean, boolean)
*/
public void setScrollPosition(int position, float positionOffset, boolean updateSelectedTabView) {
setScrollPosition(position, positionOffset, updateSelectedTabView, true);
}
/**
* Set the scroll position of the {@link TabLayout}.
*
* @param position Position of the tab to scroll.
* @param positionOffset Value from [0, 1) indicating the offset from {@code position}.
* @param updateSelectedTabView Whether to draw the tab at the specified position + positionOffset
* as selected.
* <p>Note that calling the method with {@code updateSelectedTabView = true}
* <em>does not</em> select a tab at the specified position, but only <em>draws it
* as selected</em>. This can be useful for when the TabLayout behavior needs to be linked to
* another view, such as {@link androidx.viewpager.widget.ViewPager}.
* @param updateIndicatorPosition Whether to set the indicator to the specified position and
* offset.
* <p>Note that calling the method with {@code updateIndicatorPosition = true}
* <em>does not</em> select a tab at the specified position, but only updates the indicator
* position. This can be useful for when the TabLayout behavior needs to be linked to
* another view, such as {@link androidx.viewpager.widget.ViewPager}.
* @see #setScrollPosition(int, float, boolean)
*/
public void setScrollPosition(
int position,
float positionOffset,
boolean updateSelectedTabView,
boolean updateIndicatorPosition) {
setScrollPosition(
position,
positionOffset,
updateSelectedTabView,
updateIndicatorPosition,
/* alwaysScroll= */ true);
}
void setScrollPosition(
int position,
float positionOffset,
boolean updateSelectedTabView,
boolean updateIndicatorPosition,
boolean alwaysScroll) {
final int roundedPosition = Math.round(position + positionOffset);
if (roundedPosition < 0 || roundedPosition >= slidingTabIndicator.getChildCount()) {
return;
}
// Set the indicator position, if enabled
if (updateIndicatorPosition) {
slidingTabIndicator.setIndicatorPositionFromTabPosition(position, positionOffset);
}
// Now update the scroll position, canceling any running animation
if (scrollAnimator != null && scrollAnimator.isRunning()) {
scrollAnimator.cancel();
}
int scrollXForPosition = calculateScrollXForTab(position, positionOffset);
int scrollX = getScrollX();
// If the position is smaller than the selected tab position, the position is getting larger
// to reach the selected tab position so scrollX is increasing.
// We only want to update the scroll position if the new scroll position is greater than
// the current scroll position.
// Conversely if the position is greater than the selected tab position, the position is
// getting smaller to reach the selected tab position so scrollX is decreasing.
// We only update the scroll position if the new scroll position is less than the current
// scroll position.
// Lastly if the position is equal to the selected position, we want to set the scroll
// position which also updates the selected tab view and the indicator.
boolean toMove =
(position < getSelectedTabPosition() && scrollXForPosition >= scrollX)
|| (position > getSelectedTabPosition() && scrollXForPosition <= scrollX)
|| (position == getSelectedTabPosition());
// If the layout direction is RTL, the scrollXForPosition and scrollX comparisons are
// reversed since scrollX values remain the same in RTL but tab positions go RTL.
if (getLayoutDirection() == View.LAYOUT_DIRECTION_RTL) {
toMove =
(position < getSelectedTabPosition() && scrollXForPosition <= scrollX)
|| (position > getSelectedTabPosition()
&& scrollXForPosition >= scrollX)
|| (position == getSelectedTabPosition());
}
// We want to scroll if alwaysScroll is true, the viewpager is being dragged, or if we should
// scroll by the rules above.
if (toMove || viewPagerScrollState == SCROLL_STATE_DRAGGING || alwaysScroll) {
scrollTo(position < 0 ? 0 : scrollXForPosition, 0);
}
// Update the 'selected state' view as we scroll, if enabled
if (updateSelectedTabView) {
setSelectedTabView(roundedPosition);
}
}
/**
* Add a tab to this layout. The tab will be added at the end of the list. If this is the first
* tab to be added it will become the selected tab.
*
* @param tab Tab to add
*/
public void addTab(@NonNull Tab tab) {
addTab(tab, tabs.isEmpty());
}
/**
* Add a tab to this layout. The tab will be inserted at <code>position</code>. If this is the
* first tab to be added it will become the selected tab.
*
* @param tab The tab to add
* @param position The new position of the tab
*/
public void addTab(@NonNull Tab tab, int position) {
addTab(tab, position, tabs.isEmpty());
}
/**
* Add a tab to this layout. The tab will be added at the end of the list.
*
* @param tab Tab to add
* @param setSelected True if the added tab should become the selected tab.
*/
public void addTab(@NonNull Tab tab, boolean setSelected) {
addTab(tab, tabs.size(), setSelected);
}
/**
* Add a tab to this layout. The tab will be inserted at <code>position</code>.
*
* @param tab The tab to add
* @param position The new position of the tab
* @param setSelected True if the added tab should become the selected tab.
*/
public void addTab(@NonNull Tab tab, int position, boolean setSelected) {
if (tab.parent != this) {
throw new IllegalArgumentException("Tab belongs to a different TabLayout.");
}
configureTab(tab, position);
addTabView(tab);
if (setSelected) {
tab.select();
}
}
private void addTabFromItemView(@NonNull TabItem item) {
final Tab tab = newTab();
if (item.text != null) {
tab.setText(item.text);
}
if (item.icon != null) {
tab.setIcon(item.icon);
}
if (item.customLayout != 0) {
tab.setCustomView(item.customLayout);
}
if (!TextUtils.isEmpty(item.getContentDescription())) {
tab.setContentDescription(item.getContentDescription());
}
addTab(tab);
}
private boolean isScrollingEnabled() {
return getTabMode() == MODE_SCROLLABLE || getTabMode() == MODE_AUTO;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
// When a touch event is intercepted and the tab mode is fixed, do not continue to process the
// touch event. This will prevent unexpected scrolling from occurring in corner cases (i.e. a
// layout in fixed mode that has padding should not scroll for the width of the padding).
return isScrollingEnabled() && super.onInterceptTouchEvent(event);
}
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getActionMasked() == MotionEvent.ACTION_SCROLL && !isScrollingEnabled()) {
return false;
}
return super.onTouchEvent(event);
}
/**
* @deprecated Use {@link #addOnTabSelectedListener(OnTabSelectedListener)} and {@link
* #removeOnTabSelectedListener(OnTabSelectedListener)}.
*/
@Deprecated
public void setOnTabSelectedListener(@Nullable OnTabSelectedListener listener) {
setOnTabSelectedListener((BaseOnTabSelectedListener) listener);
}
/**
* @deprecated Use {@link #addOnTabSelectedListener(OnTabSelectedListener)} and {@link
* #removeOnTabSelectedListener(OnTabSelectedListener)}.
*/
@Deprecated
public void setOnTabSelectedListener(@Nullable BaseOnTabSelectedListener listener) {
// The logic in this method emulates what we had before support for multiple
// registered listeners.
if (selectedListener != null) {
removeOnTabSelectedListener(selectedListener);
}
// Update the deprecated field so that we can remove the passed listener the next
// time we're called
selectedListener = listener;
if (listener != null) {
addOnTabSelectedListener(listener);
}
}
/**
* Add a {@link TabLayout.OnTabSelectedListener} that will be invoked when tab selection changes.
*
* <p>Components that add a listener should take care to remove it when finished via {@link
* #removeOnTabSelectedListener(OnTabSelectedListener)}.
*
* @param listener listener to add
*/
public void addOnTabSelectedListener(@NonNull OnTabSelectedListener listener) {
addOnTabSelectedListener((BaseOnTabSelectedListener) listener);
}
/**
* Add a {@link TabLayout.BaseOnTabSelectedListener} that will be invoked when tab selection
* changes.
*
* <p>Components that add a listener should take care to remove it when finished via {@link
* #removeOnTabSelectedListener(BaseOnTabSelectedListener)}.
*
* @param listener listener to add
* @deprecated use {@link #addOnTabSelectedListener(OnTabSelectedListener)}
*/
@Deprecated
public void addOnTabSelectedListener(@Nullable BaseOnTabSelectedListener listener) {
if (!selectedListeners.contains(listener)) {
selectedListeners.add(listener);
}
}
/**
* Remove the given {@link TabLayout.OnTabSelectedListener} that was previously added via {@link
* #addOnTabSelectedListener(OnTabSelectedListener)}.
*
* @param listener listener to remove
*/
public void removeOnTabSelectedListener(@NonNull OnTabSelectedListener listener) {
removeOnTabSelectedListener((BaseOnTabSelectedListener) listener);
}
/**
* Remove the given {@link TabLayout.BaseOnTabSelectedListener} that was previously added via
* {@link #addOnTabSelectedListener(BaseOnTabSelectedListener)}.
*
* @param listener listener to remove
* @deprecated use {@link #removeOnTabSelectedListener(OnTabSelectedListener)}
*/
@Deprecated
public void removeOnTabSelectedListener(@Nullable BaseOnTabSelectedListener listener) {
selectedListeners.remove(listener);
}
/** Remove all previously added {@link TabLayout.OnTabSelectedListener}s. */
public void clearOnTabSelectedListeners() {
selectedListeners.clear();
}
/**
* Create and return a new {@link Tab}. You need to manually add this using {@link #addTab(Tab)}
* or a related method.
*
* @return A new Tab