1、 build.gradle文件中加入
compile 'com.android.support:design:22.2.0'
2、写Xml文件,注意TabLayout的三个属性
app:tabIndicatorColor="#0f0" 每个tab下方的下划线的颜色
app:tabSelectedTextColor="#00f" 被选中的tab的文本颜色
app:tabTextColor="#f00" 未被选中的tab的文本颜色
布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"> <android.support.design.widget.TabLayout
android:id="@+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#777"
app:tabIndicatorColor="#0f0"
app:tabSelectedTextColor="#00f"
app:tabTextColor="#f00"
/> <android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#cccc"
/> </LinearLayout> activity_main.xml
package com.xqx.com.tablayoutdemo; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.os.Bundle; import java.util.ArrayList;
import java.util.List; public class MainActivity extends FragmentActivity { private TabLayout tabLayout;
private ViewPager viewPager; //四个fragment
private OneFragment oneFragment;
private TwoFragment twoFragment;
private ThreeFragment threeFragment;
private FourFragment fourFragment; //适配器
private MyAdapter adapter; private List<Fragment> fragments; //fragment集合
private List<String> titles; //tab标题集合
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); tabLayout = (TabLayout) findViewById(R.id.tablayout);
viewPager = (ViewPager) findViewById(R.id.viewpager); //创建四个Fragment对象
oneFragment = new OneFragment();
twoFragment = new TwoFragment();
threeFragment = new ThreeFragment();
fourFragment = new FourFragment(); //将四个Fragment对象添加到集合中
fragments = new ArrayList<>();
fragments.add(oneFragment);
fragments.add(twoFragment);
fragments.add(threeFragment);
fragments.add(fourFragment); //给Tab添加标题
titles = new ArrayList<>();
titles.add("one");
titles.add("two");
titles.add("three");
titles.add("four"); //创建适配器
adapter = new MyAdapter(getSupportFragmentManager(),fragments,titles);
//viewpager绑定适配器
viewPager.setAdapter(adapter);
//tabLayout绑定viewpager
tabLayout.setupWithViewPager(viewPager); } } MainActivity.java
mainactivity