转载自:http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0731/3247.html
在开发中,我们常常需要ViewPager结合Fragment一起使用,如下图:

我们可以使用三方开源的PagerSlidingTabStrip去实现,或者viewpagerindicator,我一般都偏向前者。现在我们可以使用Design support library库的TabLayout去实现了。最终的效果图:

效果图
创建布局
[crayon-59131334e9c13713362622/]
在xml添加TabLayout,如同ViewPager,直接
android.support.design.widget.TabLayout
即可。还有其他的属性我会在代码中设置。
创建Fragment
[crayon-59131334e9c1d032932318/]
其中Fragment的布局为:
[crayon-59131334e9c27273134452/]
ViewPager的适配器
[crayon-59131334e9c2a772302072/]
设置TabLayout
[crayon-59131334e9c2d183116255/]
这里提几点我遇到的问题
[crayon-59131334e9c30320361476/]
开始我设置的是:
[crayon-59131334e9c32341472263/]
运行后,三个TabLayout标签挤到一块去了。如下:

查看api,找到结果了。这个tabmode有两个属性值:
- MODE_FIXED:Fixed tabs display all tabs concurrently and are best used with content that benefits from quick pivots between tabs.
- MODE_SCROLLABLE:Scrollable tabs display a subset of tabs at any given moment, and can contain longer tab labels and a larger number of tabs.
不做过多的解释,MODE_SCROLLABLE适合很多tabs的情况。
此外:
setupWithViewPager必须在ViewPager.setAdapter()之后调用
以上就是最基本的用法,是不是很简单。哈~
定义TabLayout的样式
默认的情况下,TabLayout的tab indicator的颜色是Material Design中的accent color(#009688),我们可以稍作修改:
[crayon-59131334e9c34074910816/]
在布局中使用:
[crayon-59131334e9c36809129664/]
还有一些其他的样式可供选择:
[crayon-59131334e9c38581975791/]