使用View.post滑动tablayout到指定位置
tabLayout.post(new Runnable() {
@Override
public void run() {
tabLayout.getTabAt(position).select();
}
});
这里有一个小坑,第一次滑动到0位置时OnTabSelectedListener.onTabSelected不会被调用到,
查看了select源码发现是调用dispatchTabReselected 最后调用OnTabSelectedListener.onTabReselected
public void select() {
if (parent == null) {
throw new IllegalArgumentException("Tab not attached to a TabLayout");
}
parent.selectTab(this);
}
----->
public void selectTab(@Nullable Tab tab) {
selectTab(tab, true);
}
------>
public void selectTab(@Nullable final Tab tab, boolean updateIndicator) {
final Tab currentTab = selectedTab;
//由于tablayou 默认选中第一项,第一次滑动位置0是调用了dispatchTabReselected
if (currentTab == tab) {
if (currentTab != null) {
dispatchTabReselected(tab);
animateToTab(tab.getPosition());
}
} else {
final int newPosition = tab != null ? tab.getPosition() : Tab.INVALID_POSITION;
if (updateIndicator) {
if ((currentTab == null || currentTab.getPosition() == Tab.INVALID_POSITION)
&& newPosition != Tab.INVALID_POSITION) {
// If we don't currently have a tab, just draw the indicator
setScrollPosition(newPosition, 0f, true);
} else {
animateToTab(newPosition);
}
if (newPosition != Tab.INVALID_POSITION) {
setSelectedTabView(newPosition);
}
}
// Setting selectedTab before dispatching 'tab unselected' events, so that currentTab's state
// will be interpreted as unselected
selectedTab = tab;
if (currentTab != null) {
dispatchTabUnselected(currentTab);
}
if (tab != null) {
dispatchTabSelected(tab);
}
}
}
------>
private void dispatchTabReselected(@NonNull final Tab tab) {
for (int i = selectedListeners.size() - 1; i >= 0; i--) {
selectedListeners.get(i).onTabReselected(tab);
}
}
最后修改业务流程
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
getData();
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
getData();
}
});