前言
之前在另外一篇中用Fragment和button实现了点击切换Fragment的效果,比较简陋。这次改用ViewPager+TabLayout 实现联动的效果。
实现效果
ViewPager 多个页面滑动
TabLayout 和 ViewPager绑定,实现Fragment和标签绑定
TabLayout的自定义标签以及选中颜色改变
效果图
![c4892496e0fd?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation](https://www.jianshu.com/p/c4892496e0fd?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation)
效果图
思路分析
ViewPager用来放Fragment,并且实现滑动的效果。(原谅我最近才知道这个控件,所以才会有上一篇用Fragment+Button来实现切换。PS:经常百度copy的后遗症┗( T﹏T )┛)
TabLayout 用来放Fragment对应标题。标题只是文字话,需要重写FragmentPagerAdapter的getPageTitle()方法来获取标题,如果要用图标或者复杂的标题可以用TabLayout的setCustomView()将自定义控件放入Tab中。
通过TabLayout的setupWithViewPager()方法来实现TabLayout和ViewPager联动。
布局文件
activity_tab_layout_custom_title.xml
主界面布局文件包含一个ViewPager和一个TabLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#FFFFFF"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
android:id="@+id/contextViewPager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1">
android:id="@+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="58dp"
app:tabMinWidth="80dp"
app:tabIndicatorColor="#0000000