Bootstrap

Android控件-TabLayout使用介绍

public Fragment getItem(int position) {

return tabFragmentList.get(position);

}

@Override

public int getCount() {

return tabFragmentList.size();

}

@Nullable

@Override

public CharSequence getPageTitle(int position) {

return tabs[position];

}

});

//设置TabLayout和ViewPager联动

tabLayout.setupWithViewPager(viewPager,false);

}

}

简单的3步:

  1. 为TabLayout添加tab

  2. 给ViewPager设置adapter

  3. 设置TabLayout和ViewPager联动

看看运行结果:

在这里插入图片描述

好了,基本的功能已经实现了。这里有个需要注意的点:

就是在给ViewPager设置Adapter的时候,一定要重写getPageTitle(int position)方法,不然TabLayout中的标签是看不到的,即使在addTab时newTab().setText(tabs[i])也没用。原因很简单,是在tabLayout.setupWithViewPager的时候,TabLayout中先将所有tabs remove了,然后取的PagerAdapter中的getPageTitle返回值添加的tab。看下源码

@ViewPager.DecorView

public class TabLayout extends HorizontalScrollView {

private void setupWithViewPager(

@Nullable final ViewPager viewPager, boolean autoRefresh, boolean implicitSetup) {

if (viewPager != null) {

this.viewPager = viewPager;

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);

}

} else {

// We’ve been given a null ViewPager so we need to clear out the internal state,

// listeners and observers

this.viewPager = null;

setPagerAdapter(null, false);

}

}

void setPagerAdapter(@Nullable final PagerAdapter adapter, final boolean addObserver) {

// Finally make sure we reflect the new adapter

populateFromPagerAdapter();

}

void populateFromPagerAdapter() {

removeAllTabs();

if (pagerAdapter != null) {

final int adapterCount = pagerAdapter.getCount();

for (int i = 0; i < adapterCount; i++) {

addTab(newTab().setText(pagerAdapter.getPageTitle(i)), false);

}

}

}

}

可以看到populateFromPagerAdapter方法中执行了removeAllTabs()方法,然后取pagerAdapter.getPageTitle(i)方法返回值重新添加tab,所以记得重写getPageTitle方法。

除了在代码里面动态的添加tab,还可以直接在xml中进行添加TabItem。

<com.google.android.material

;