一、前言
在开发中,我们常常需要 ViewPager 结合 Fragment一起使用,来实现多页签的切换效果。在以前,我们有以下一系列第三方库来帮我们实现:
而现在,我们可以使用Design support library 库的 TabLayout 来实现了。
二、最终效果图
三、TabLayout 的使用
1. 添加依赖
由于 TabLayout 在 design 包内,所以首先需要在 app 目录下的 build.gradle 中添加以下依赖:
1
2
3
4dependencies {
...
compile 'com.android.support:design:23.4.0'
}
2. 创建布局
布局相当简单,只要添加 TabLayout 和 ViewPager 的布局即可:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23// layout/activity_main.xml
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
android:id="@+id/tab_layout"
style="@style/TabLayoutStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="@android:color/white"/>
还有其他的属性我习惯在style文件中设置:
1
2
3
4
5
6
7
8
9
10
11
12
13// values/styles.xml
@color/colorPrimary
@color/colorPrimary
@style/TabTextAppearence
0dp
16sp
false
3. 创建 Fragment1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38package com.sherlockshi.badgedtablayoutpractise;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;<