首先在布局文件中添加TabLayout:
<android.support.design.widget.TabLayout android:id="@+id/ivy_module_widget_shop_tab_layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorPrimary" app:tabIndicatorColor="@color/white" app:tabSelectedTextColor="@color/white" app:tabTextColor="@color/gray" > </android.support.design.widget.TabLayout>
app:tabIndicatorColor="@color/white",app:tabSelectedTextColor="@color/white",app:tabTextColor="@color/gray" 分别表示游标颜色,标签选中时文字颜色,标签未选中时文字颜色,需要在根布局中添加一个命名空间:xmlns:app="http://schemas.android.com/apk/res-auto"
在Activity中:
tabList.add("online"); tabList.add("local"); tabLayout.setTabMode(TabLayout.MODE_FIXED); tabLayout.addTab(tabLayout.newTab()); tabLayout.addTab(tabLayout.newTab()); myViewPagerAdapter = new MyViewPagerAdapter(); viewPager.setAdapter(myViewPagerAdapter); tabLayout.setupWithViewPager(viewPager);
在PagerAdapter中重写getPagerTitle方法:
@Override public CharSequence getPageTitle(int position) { return tabList.get(position); }
其中tabList为一个String类型的List,表示标签的名称