在项目中使用viewpager的时候大多数都是和TabPagerIndicator结合使用,TabPagerIndicator是第三方的,使用起来比较繁琐;
2015谷歌大会官方发布了TabLayout,可以很简单很完美的实现这种效果;
因为是官方发布的,所以使用起来不用任何第三方的东西;而且非常简单明了;
同样,如果想要使用Tablayout必须在build中配置:
- dependencies {
- compile 'com.android.support:design:23.1.1'
- }
先看下布局:
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:app="http://schemas.android.com/apk/res-auto"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- tools:context="www.tablayout.com.tablayoutdemo.MainActivity">
-
- <!--
- app:tabIndicatorColor="@color/white" // 下方滚动的下划线颜色
- app:tabSelectedTextColor="@color/gray" // tab被选中后,文字的颜色
- app:tabTextColor="@color/white" // tab默认的文字颜色
- app:tabMode="scrollable" //设置标题滑动模式
- -->
- <android.support.design.widget.TabLayout
- android:id="@+id/tablayout"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:background="@android:color/holo_blue_light"
- app:tabIndicatorColor="@android:color/holo_red_dark"
- app:tabSelectedTextColor="@android:color/holo_red_dark"
- app:tabTextColor="@android:color/background_dark"
- app:tabMode="scrollable"
- />
-
- <android.support.v4.view.ViewPager
- android:id="@+id/viewpager"
- android:layout_width="match_parent"
- android:layout_height="0dp"
- android:layout_weight="1" />
-
- </LinearLayout>
代码使用起来也非常简单
第一步:初始化ViewPager并设置adapter
第二步:给Tablayout设置标题
第三部:将Tablayout和ViewPager关联到一起
- <span style="white-space:pre"> </span>
- viewPager = (ViewPager) findViewById(R.id.viewpager);
- viewPager.setAdapter(new MyViewPagerAdapter(getSupportFragmentManager(), fragmentList));
-
-
- tabLayout = (TabLayout) findViewById(R.id.tablayout);
-
- tabLayout.addTab(tabLayout.newTab().setText("UFC"));
- tabLayout.addTab(tabLayout.newTab().setText("武林风"));
- tabLayout.addTab(tabLayout.newTab().setText("昆仑决"));
- tabLayout.addTab(tabLayout.newTab().setText("荣耀"));
- tabLayout.addTab(tabLayout.newTab().setText("勇士的崛起"));
- tabLayout.addTab(tabLayout.newTab().setText("K-1"));
-
-
- tabLayout.setupWithViewPager(viewPager);
好了,正常情况下就到此结束了,但是我在写这个demo的时候碰到一个坑:
标题死活显示不出来,浪费了很长时间,最后在Tablayout关联Viewpager之后添加从新设置下标题即可:
-
- tabLayout.getTabAt(0).setText("UFC");
- tabLayout.getTabAt(1).setText("武林风");
- tabLayout.getTabAt(2).setText("昆仑决");
- tabLayout.getTabAt(3).setText("荣耀");
- tabLayout.getTabAt(4).setText("勇士的崛起");
- tabLayout.getTabAt(5).setText("K-1");
总体来说Tablayout完全可以代替TabPagerIndicator,而且使用起来比较简单,最重要的还是官方的;
点击打开链接免费下载源码