ViewPager+Fragment+TabLayOut

布局文件中使用TabLayout和ViewPager



新建adapter继承FragmentPagerAdapter

public class MyPageAdapter extends FragmentPagerAdapter {
    ArrayList datas;
    ArrayList titles;

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

    public void setData(ArrayList datas) {
        this.datas = datas;
    }

    public void setTitles(ArrayList titles) {
        this.titles = titles;
    }

    @Override
    public Fragment getItem(int position) {
        return datas == null ? null : datas.get(position);
    }

    @Override
    public int getCount() {
        return datas == null ? 0 : datas.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return titles == null ? null : titles.get(position);
    }
}

在需要使用的页面添加如下代码

MyPageAdapter myPageAdapter = new MyPageAdapter(getFragmentManager());

ArrayList datas = new ArrayList();
datas.add(new AFragment());
datas.add(new BFragment());
datas.add(new CFragment());
myPageAdapter.setData(datas);

ArrayList titles = new ArrayList();
titles.add("A");
titles.add("B");
titles.add("C");
myPageAdapter.setTitles(titles);

使ViewPager和TabLayout相关联

TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
// 将适配器设置进ViewPager
 viewPager.setAdapter(myPageAdapter);
// 将ViewPager与TabLayout相关联
 tabLayout.setupWithViewPager(viewPager);

你可能感兴趣的:(ViewPager+Fragment+TabLayOut)