依赖 design:26.0.0包
MainActivity 类
public class MainActivity extends FragmentActivity {
private List<Fragment> fragmentList = new ArrayList<>();
private ViewPager viewPager;
private TabLayout tabLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
//第一步:初始化ViewPager并设置adapter
viewPager = (ViewPager) findViewById(R.id.homefragment_vp);
viewPager.setAdapter(new MyViewPagerAdapter(getSupportFragmentManager(), fragmentList));
//第二步:初始化Tablayout,给ViewPager设置标题(选项卡)
tabLayout = (TabLayout) findViewById(R.id.homefragment_tablelayouts);
tabLayout.addTab(tabLayout.newTab().setText("周一"));//添加tab选项卡
tabLayout.addTab(tabLayout.newTab().setText("周二"));
tabLayout.addTab(tabLayout.newTab().setText("周三"));
tabLayout.addTab(tabLayout.newTab().setText("周四"));
tabLayout.addTab(tabLayout.newTab().setText("周五"));
tabLayout.addTab(tabLayout.newTab().setText("昨天"));
tabLayout.addTab(tabLayout.newTab().setText("今天"));
//第三步:关联ViewPager
tabLayout.setupWithViewPager(viewPager);
//在关联ViewPager之后添加如下代码,前三步不用更改
tabLayout.getTabAt(0).setText("周一");
tabLayout.getTabAt(1).setText("周二");
tabLayout.getTabAt(2).setText("周三");
tabLayout.getTabAt(3).setText("周四");
tabLayout.getTabAt(4).setText("周五");
tabLayout.getTabAt(5).setText("昨天");
tabLayout.getTabAt(6).setText("今天");
}
private void initData() {
fragmentList.add(new PagerFragment1());
fragmentList.add(new PagerFragment2());
fragmentList.add(new PagerFragment3());
fragmentList.add(new PagerFragment4());
fragmentList.add(new PagerFragment5());
fragmentList.add(new PagerFragment6());
fragmentList.add(new PagerFragment7());
}
}
适配器:
public class MyViewPagerAdapter extends FragmentPagerAdapter{
private final List<Fragment> fragmentList;
public MyViewPagerAdapter(FragmentManager fm, List<Fragment> fragmentList) {
super(fm);
this.fragmentList=fragmentList;
}
@Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
@Override
public int getCount() {
return fragmentList.size();
}
}
别忘了写Fragment
布局:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<android.support.design.widget.TabLayout
android:id="@+id/homefragment_tablelayouts"
android:layout_width="0dp"
android:layout_height="30dp"
app:tabIndicatorHeight="2dp"
android:layout_weight="1"
app:tabSelectedTextColor="#000000"
app:tabMode="scrollable"
>
</android.support.design.widget.TabLayout>
</LinearLayout>
<android.support.v4.view.ViewPager
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/homefragment_vp"
></android.support.v4.view.ViewPager>