In ViewPager, addOnPageChangeListener and
What's the difference between addOnTabSelectedListener in TabLayout?
Both seem like listeners to tap changes, but I don't know the difference.
TabPagerAdapter pagerAdapter = new TabPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(pagerAdapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
// // Set TabSelectedListener
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
In the above code, ViewPager's addOnPageChangeListener is intended to inform TabLayout when a page in ViewPager is scrolled. For example, when a user swipes ViewPager from page 1 to page 2, the tab will also expect the selection to change from page 1 to 2. This is to synchronize the scroll state of ViewPager with the UI state of TabLayout. Annotating the code will confirm that this part is not working properly. If you look at the TabLayout.TabLayoutOnPageChangeListener code passed to the actual parameters, the action is as follows (some of the code is omitted because it is long).
@Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
...
final boolean updateText = mScrollState != SCROLL_STATE_SETTLING ||mPreviousScrollState == SCROLL_STATE_DRAGGING;
final boolean updateIndicator = !(mScrollState == SCROLL_STATE_SETTLING && mPreviousScrollState == SCROLL_STATE_IDLE);
tabLayout.setScrollPosition(position, positionOffset, updateText, updateIndicator);
}
@Override
public void onPageSelected(int position) {
final boolean updateIndicator = mScrollState == SCROLL_STATE_IDLE
|| || (mScrollState == SCROLL_STATE_SETTLING
&& mPreviousScrollState == SCROLL_STATE_IDLE);
tabLayout.selectTab(tabLayout.getTabAt(position), updateIndicator);
}
TabLayout's addOnTabSelectedListener is an API to provide the selection status of tabs. Depending on your implementation, this function may or may not be used. It looks similar to addOnPageChangeListener, but the difference is that a callback specializing in TabLayout is invoked.
© 2024 OneMinuteCode. All rights reserved.