android TabLayout+ViewPager配合使用

1.在项目app下的Module中添加依赖

compile 'com.android.support:design:25.2.0'

2.相应的布局文件


 
        

3.构建adapter

public class MyPagerAdapter extends FragmentPagerAdapter {
    private Context context;
    private List fragmentList;
    private List list_Title;
    public MyPagerAdapter(FragmentManager fm,Context context,List fragmentList,List list_Title) {
        super(fm);
        this.context = context;
        this.fragmentList = fragmentList;
        this.list_Title = list_Title;
    }

    @Override
    public Fragment getItem(int position) {
        return fragmentList.get(position);
    }
    @Override
    public int getCount() {
        return list_Title.size();
    }
    /**
     * //此方法用来显示tab上的名字
     * @param position
     * @return
     */
    @Override
    public CharSequence getPageTitle(int position) {
        return list_Title.get(position);
    }

4.tablayout和ViewPager联动

 fragmentList = new ArrayList<>();
        list_Title = new ArrayList<>();
        fragmentList.add(new OneFragment());
        fragmentList.add(new TwoFragment());
        list_Title.add("one");
        list_Title.add("two");
        viewpager.setAdapter(new MyPagerAdapter(getSupportFragmentManager(),HelpCenterActivity.this,fragmentList,list_Title));
tablayout.setupWithViewPager(viewpager);//此方法就是让tablayout和ViewPager联动

效果图如下


android TabLayout+ViewPager配合使用_第1张图片
这里写图片描述

详细代码已经贴出 经过以上步骤就顶部导航切换了

你可能感兴趣的:(android TabLayout+ViewPager配合使用)