TabLayout使用setupWithViewPager()方法绑定Viewpager后不显示文字
使用TabLayout结合ViewPager的时候,一般都会用到setupWithViewPager()这个方法让他俩联动起来,但是如果不注意,这儿有一个需要注意的坑。。。
mTabLayout.setupWithViewPager(mViewPager);
源码:
final PagerAdapter adapter = viewPager.getAdapter();
if (adapter != null) {
// Now we'll populate ourselves from the pager adapter, adding an observer if
// autoRefresh is enabled
setPagerAdapter(adapter, autoRefresh);
}
没啥问题,继续跟一下setPagerAdapter(adapter, autoRefresh);这个方法
源码如下:
void setPagerAdapter(@Nullable final PagerAdapter adapter, final boolean addObserver) {
if (mPagerAdapter != null && mPagerAdapterObserver != null) {
// If we already have a PagerAdapter, unregister our observer
mPagerAdapter.unregisterDataSetObserver(mPagerAdapterObserver);
}
mPagerAdapter = adapter;
if (addObserver && adapter != null) {
// Register our observer on the new adapter
if (mPagerAdapterObserver == null) {
mPagerAdapterObserver = new PagerAdapterObserver();
}
adapter.registerDataSetObserver(mPagerAdapterObserver);
}
// Finally make sure we reflect the new adapter
populateFromPagerAdapter();
}
也没啥问题啊。。。。看见最后有这个方法populateFromPagerAdapter();,好奇点进去看看~
源码:
void populateFromPagerAdapter() {
removeAllTabs();
if (mPagerAdapter != null) {
final int adapterCount = mPagerAdapter.getCount();
for (int i = 0; i < adapterCount; i++) {
addTab(newTab().setText(mPagerAdapter.getPageTitle(i)), false);
}
// Make sure we reflect the currently set ViewPager item
if (mViewPager != null && adapterCount > 0) {
final int curItem = mViewPager.getCurrentItem();
if (curItem != getSelectedTabPosition() && curItem < getTabCount()) {
selectTab(getTabAt(curItem));
}
}
removeAllTabs(); FUCK……..
什么鬼。。。未经允许,将我添加的Tab都干掉了????
嗯,现在明白了吧。。。是系统给你删除了,,so解决办法就是
一:
@Override
public CharSequence getPageTitle(int position) {
return titles.get(position);
}
适配器里边重写他。。。
二:
setupWithViewPager()方法之后,重新赋值文本。。。。
tablayout_vp.getTabAt(0).setText(“”);