Android自定义TabLayout后ViewPager与TabLayout互相控制切换
正常的Android原生TabLayout与ViewPager搭配使用,当TabLayout调用setupWithViewPager与ViewPager互相捆绑以后,就实现了原生的TabLayout与ViewPager的互相控制。
但是,当自定义TabLayout后,由于setupWithViewPager本身会将删掉所有TabLayout的子View,那么自定义的View就会失效,因此自定义TabLayout后,就无法再使用setupWithViewPager实现TabLayout与ViewPager的双向互相控制了。详情见附录文章1。
一些材料说可以在ViewPager里面添加OnPageChangeListener,然后在OnPageChangeListener的onPageScrolled里面使用TabLayout的setScrollPosition方法,在ViewPager中控制TabLayout的切换,貌似无效。TabLayout的源代码也指出了setScrollPosition并不会更新选中Tab的UI:
/**
* Set the scroll position of the tabs. This is useful for when the tabs are being displayed as
* part of a scrolling container such as {@link android.support.v4.view.ViewPager}.
* <p>
* Calling this method does not update the selected tab, it is only used for drawing purposes.
*
* @param position current scroll position
* @param positionOffset Value from [0, 1) indicating the offset from {@code position}.
* @param updateSelectedText Whether to update the text's selected state.
*/
public void setScrollPosition(int position, float positionOffset, boolean updateSelectedText) {
setScrollPosition(position, positionOffset, updateSelectedText, true);
}
经过研究TabLayout的源代码最终发现,当自定义TabLayout后,如果仍然希望自定义的TabLayout与ViewPager双向互相控制,可以用下面的方式实现:
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
附:
1,《Android TabLayout定制CustomView与ViewPager交互双向联动》链接:https://blog.csdn.net/zhangphil/article/details/48934039