ViewPager+Fragment+TabLayout案例

第一种方法:

1.xml设置TabLayout与ViewPager




 

 

2.为ViewPager创建适配器

    public class MianAdapter extends FragmentPagerAdapter{
    private ArrayList fragments;
   public MainAdapter(FragmentManager fm,     ArrayList fragments) {
          super(fm);
          this.fragments = fragments;
}
    public MainAdapter(FragmentManager fm) {
          super(fm);
}

@Override
    public Fragment getItem(int i) {
          return fragments.get(i);
}

@Override
    public int getCount() {
        return fragments.size();
}
}

3.代码设置TabLayout和ViewPager绑定
//找控件
//数据源
//创建适配器

 MainAdapter mainAdapter=new  MainAdapter(getSupportFragmentManager(),fragments)
//设置适配器
vp.setAdapter(mainAdapter);
  //联动
  tab.setupWithViewPager(vp);
  tab.getTabAt(0).setText("首页");
  tab.getTabAt(1).setText("资讯");
  tab.getTabAt(2).setText("直播");
  tab.getTabAt(3).setText("我");

#######第二种方法
首先式是布局:




    
        

    

    

    



重写FragmentAdapter

 public class  MainFragmentAdapter extends FragmentPagerAdapter{L

List list;
List title;

public MyFragmentAdapter(FragmentManager fm) {
    super(fm);
    }

public MyFragmentAdapter(FragmentManager fm, List list, List title) {
    super(fm);
    this.list = list;
    this.title = title;
}

@Override
public Fragment getItem(int position) {
    return list.get(position);
}

@Override
public int getCount() {
    return list.size();
}

/*让TabLayout能获取到title*/
@Override
public CharSequence getPageTitle(int position) {
    return title.get(position);
}

}
主要是重写getPageTitle()方法
代码设置TabLayout和ViewPager绑定

 // tablayout
TabLayout tabLayout = (TabLayout)                   findViewById(R.id.tab_layout);
// vp
mViewPager = (ViewPager)     findViewById(R.id.container);

mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
  mViewPager.setAdapter(mSectionsPagerAdapter);
// 绑定,要在viewpager设置完数据后,调用此方法,否则不显示 tabs文本
        tabLayout.setupWithViewPager(mViewPager);

你可能感兴趣的:(ViewPager+Fragment+TabLayout案例)