您好,欢迎来到五一七教育网。
搜索
您的当前位置:首页使用Tablayout出现标题消失的原因:setupWithViewPager()的大坑

使用Tablayout出现标题消失的原因:setupWithViewPager()的大坑

来源:五一七教育网
TabLayout使用addTab方法添加标题,调用setupWithViewPager方法绑定ViewPager
tabLayout.addTab(tabLayout.newTab().setText("全部"));
tabLayout.addTab(tabLayout.newTab().setText("Ping²it"));
tabLayout.addTab(tabLayout.newTab().setText("同款"));
allArtPager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager(),fragmentList));
allArtPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
allArtPager.setCurrentItem(articleClass);

tabLayout.setupWithViewPager(allArtPager);

这时候添加的标题却不显示了
查看TabLayout封装的setupWithViewPager方法的源码。

removeAllTabs();它竟然把之前添加的title全部被清空,自己又new新的title,所以我们之前添加的标题都不见了。

对于这个问题我有两种解决办法:

方法一:可以执行完setupWithViewPager()后,再添加标题,
       tabLayout.setupWithViewPager(allArtPager);
       tabLayout.getTabAt(0).setText("全部");
tabLayout.getTabAt(1).setText("Ping²it");
tabLayout.getTabAt(2).setText("同款");

方法二:查看源码,TabLayout执行完removeAllTabs后,new新的Tabs,它调用的PagerAdapter中的方法getPageTitle();所以我们可以在PagerAdapter中添加Titles


public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
private ArrayList<Fragment> fragments;
private String[] titles = new String[]{"全部", "Ping²it", "同款", "尖儿货", "场景","BRAND", "态度", "MESSAGE"};
public MyFragmentPagerAdapter(FragmentManager fragmentManager, ArrayList<Fragment> fragments) {
super(fragmentManager);
this.fragments=fragments;
}

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

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

@Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}

个人感觉还是第二种方法方便实用,Tablayout源码中使用removeAllTabs,又调用PagerAdapter的getPageTitle()方法,本身就是想在PagerAdapter中获取title。



转载于:https://www.cnblogs.com/donghaifeng-2016/p/6369729.html

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- 517ttc.cn 版权所有 赣ICP备2024042791号-8

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务