TabLayout和viewpager绑定的两种方式

两种方法的区别是tab的文字放在哪里,一种是在Activity中一种是在是配置中;
先第一种在Activity中:

//把需要用的Fragment放到一个集合中
List list=new ArrayList<>();
        list.add(new Frag1());
        list.add(new Frag2());
//适配器
MyAdpater adpater = new MyAdpater(getSupportFragmentManager());
        adpater.setData(list);
        page.setAdapter(adpater);
 //一个样式
tab.setTabMode(TabLayout.MODE_FIXED);
//TabLayout与viewpager联动的代码
tab.setupWithViewPager(page);
//需要几个页面new几个
tab.addTab(tab.newTab());
tab.addTab(tab.newTab());
//把需要的文字写在里面,也是要先开启
tab.getTabAt(0).setText("1");
tab.getTabAt(1).setText("2");

适配器

private List list;

    public MyAdpater(FragmentManager supportFragmentManager) {
        super(supportFragmentManager);

        this.list=new ArrayList<>();
    }

    public void setData(List list) {
        //这里一定要用this.否则会报空指针
        this.list.clear();   
        this.list.addAll(list);
        notifyDataSetChanged();
    }
    @Override
    public Fragment getItem(int i) {
        return list.get(i);
    }

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

第二种方法是在适配器中写字

//把frag和需要的文字放进集合
ArrayList list = new ArrayList<>();
        list.add(new FragA());
        list.add(new FragB());
        ArrayList list_s = new ArrayList<>();
        list_s.add("热门");
        list_s.add("热门");
PageAd ad = new PageAd(getSupportFragmentManager());
//把两个集合都放进适配器
ad.setData(list,list_s);

tab.setTabMode(TabLayout.MODE_FIXED);
 page.setAdapter(ad);
tab.setupWithViewPager(page);
tab.addTab(tab.newTab());
tab.addTab(tab.newTab());

以下是适配器

private ArrayList list;
    private ArrayList list_s;

    public PageAd(FragmentManager supportFragmentManager) {
        super(supportFragmentManager);
        this.list=new ArrayList<>();

    }
    public void setData(ArrayList list,ArrayList list_s) {
        this.list=list;
        this.list_s=list_s;
    }


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

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

//注意要把这个方法打出来把集合里的字给到
    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return list_s.get(position);
    }

你可能感兴趣的:(记录)