Tab+ViewPager可以说是Android开发中非常常见的布局了,以前实现tab布局一般使用LinearLayout或者HorizontalScrollView,还需要自己监听ViewPager的滑动。如果想实现比较顺滑的滑动效果,我们还需要自定义动画。在Android6.0之后,谷歌在design包中提供了一个widget叫TabLayout,TabLayout继承自HorizontalScrollView,可以方便地实现与ViewPager的联动,还自带顺滑的滑动效果:
1. 首先要引入android design包,在gradle中加入:
implementation 'com.android.support:design:27.1.1'
2. 在xml布局中直接跟ViewPager一起使用
<android.support.design.widget.TabLayout
android:id="@+id/about_my_tab"
android:layout_width="match_parent"
android:layout_height="55dp"
android:background="@color/white_color"
app:tabIndicatorColor="@color/main_color"
app:tabMode="fixed"
app:tabSelectedTextColor="@color/main_color"
app:tabTextAppearance="@style/MiddleTextStyle"
app:tabTextColor="@color/second_text_color" />
<android.support.v4.view.ViewPager
android:id="@+id/about_my_viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
app:tabIndicatorColor:指示器的颜色,就是底部那条线的颜色,这里选择的是绿色
app:tabMode:tab滑动模式,有fixed和scrollable两种,fixed是不可滑动,scrollable是可滑动
app:tabIndicatorHeight: 底部指示器的高度,这里使用是默认高度
app:tabSelectedTextColor: tab选中之后文字的颜色
app:tabTextAppearance:tab标题文字的大小
app:tabTextColor:tab标题文字非选中状态时的颜色
3.下一步就是在Activity中设置标题,并设置与ViewPager联动:
tabLayout= view.findViewById(R.id.about_my_tab);
tabLayout.addTab(tabLayout.newTab().setText("我的私信"));
tabLayout.addTab(tabLayout.newTab().setText("我的回复"));
设置与ViewPager的联动也异常简单:
tabLayout.setupWithViewPager(viewPager);
至此,一个TabLayout+ViewPager的布局就完成了,如果我们想在tab上加东西怎么办呢?在tab上加消息红点提示,如下图所示:
谷歌是没有帮我们准备对应的API可以直接设置这种红色badge,但是TabLayout可以设置自定义view:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckedTextView
android:id="@+id/tv_tab_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
style="@style/MiddleTextStyle"
android:text="我的回复"
android:textColor="@color/selector_tab_text"/>
<TextView
android:id="@+id/tv_message_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_alignBottom="@id/tv_tab_title"
android:layout_toEndOf="@id/tv_tab_title"
android:background="@drawable/shape_red_point"
android:gravity="center"
android:textColor="@color/white_color"
android:textSize="@dimen/text_size_10"
android:text="9"
android:visibility="visible"/>
</RelativeLayout>
写好tab的布局之后,可以使用tabLayout.setCustomView(View v)自定义tab的样式,自定义tab的view之后,需要添加listener,自行修改选中和非选中状态,而不是直接setupWithViewPager了
for (int i = 0; i < 2; i++) {
TabLayout.Tab tab = tabLayout.newTab();
tab.setCustomView(getTabView(i));
tabLayout.addTab(tab);
}
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
//自行修改选中状态
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
//自行修改非选中状态
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});