第一步:添加依赖
compile 'com.android.support:design:24.2.1'
第二步:布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabLayout
android:id="@+id/tablayout"
android:layout_width="match_parent"
android:layout_height="50dp"
app:tabTextColor="#888"
android:background="@color/colorRed"
app:tabSelectedTextColor="@color/colorWhite"
app:tabIndicatorHeight="4dp"
app:tabMode="fixed"
app:tabIndicatorColor="@color/colorWhite">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</LinearLayout>
控件属性意思解析:
app:tabIndicatorHeight="8dp" 横条选择器的高度
app:tabIndicatorColor="@color/colorPrimary" 横条选择器的颜色
app:tabMode="fixed" 有两种模式 这种是不能滑动
app:tabMode="scrollable" 默认为可滑动
app:tabTextColor="#888" 默认的字体颜色
app:tabSelectedTextColor="@color/colorWhite" 文字被选中时的颜色
第三步:在activity页面设置tablayout和viewpager的结合
public class SlideNewsFragment extends Fragment {
public TabLayout tabLayout;
public ViewPager viewPager;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View inflate = View.inflate(getActivity(), R.layout.slide_news_fragment,null);
tabLayout = (TabLayout) inflate.findViewById(R.id.tablayout);
viewPager = (ViewPager) inflate.findViewById(R.id.viewpager);
viewPager.setAdapter(new FragmentPagerAdapter(getActivity().getSupportFragmentManager()) {
String[] itemName = {"头条","NBA","汽车","笑话"};
@Override
public Fragment getItem(int position) {
switch (position){
//注意:activity中导入的包必须和碎片一致 v4包
case 0:
return new HeadLineFragment();
case 1:
return new NBAFragment();
case 2:
return new CarFragment();
case 3:
return new JokeFragment();
}
return new HeadLineFragment(); //默认返回头条页面
}
@Override
public int getCount() { //返回数据的长度
return itemName.length;
}
@Override //从数组中获取每一个页面的标题
public CharSequence getPageTitle(int position) {
return itemName[position];
}
});
tabLayout.setupWithViewPager(viewPager); //设置tablayout和viewpager的绑定
return inflate;
}
}