导入包:
compile 'com.android.support:design:22.2.1'
1、布局配置
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="@+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/top_nav_bg"
app:tabIndicatorColor="@color/white" // 下方滚动的下划线颜色
app:tabSelectedTextColor="@color/white"// // tab被选中后,文字的颜色
app:tabTextColor="@color/top_tab_textcolor_normal" // tab默认的文字颜色
/>
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
2、初始化各fragment,加入集合中,初始化tab名称列表
//初始化各fragment
FragmentMeijuList fragmentMeijuList1 = FragmentMeijuList.newInstance(TYPE1);
FragmentMeijuList fragmentMeijuList2 = FragmentMeijuList.newInstance(TYPE2);
FragmentMeijuList fragmentMeijuList3 = FragmentMeijuList.newInstance(TYPE3);
//将fragment装进列表中
List<Fragment> list_fragment = new ArrayList<>();
list_fragment.add(fragmentMeijuList1);
list_fragment.add(fragmentMeijuList2);
list_fragment.add(fragmentMeijuList3);
//将名称加载tab名字列表,正常情况下,我们应该在values/arrays.xml中进行定义然后调用
List<String> list_title = new ArrayList<>();
list_title.add("美图美句");
list_title.add("手写句子");
list_title.add("经典对白");
3、适配器实现:
public class TitleTabAdapter extends FragmentPagerAdapter {
private List<Fragment> list_fragment;
private List<String> list_Title;
public TitleTabAdapter(FragmentManager fm, List<Fragment> list_fragment, List<String> list_Title) {
super(fm);
this.list_fragment = list_fragment;
this.list_Title = list_Title;
}
@Override
public Fragment getItem(int position) {
return list_fragment.get(position);
}
@Override
public int getCount() {
return list_Title.size();
}
@Override
public CharSequence getPageTitle(int position) {
return list_Title.get(position % list_Title.size());
}
}
4、将tab名称加入tabLayout,实例化适配器进行listfragment和listtitle的绑定,
viewpager.setAdapter()实现viewpager和list_title的绑定,
tabLayout.setupWithViewPager();实现tablayout和viewpager的绑定
tabLayout.addTab(tabLayout.newTab().setText(list_title.get(0)));
tabLayout.addTab(tabLayout.newTab().setText(list_title.get(1)));
tabLayout.addTab(tabLayout.newTab().setText(list_title.get(2)));
TitleTabAdapter titleTabAdapter = new TitleTabAdapter(getChildFragmentManager(), list_fragment, list_title);
//viewpager加载adapter
viewPager.setAdapter(titleTabAdapter);
tabLayout.setupWithViewPager(viewPager);