I have 12 items in android sliding tab layout + view pager. While sliding from left to right, selected tab should be center same as play store. Please help me how to do that. In my application active tab is always left of the screen.
My approach differs a bit of the Shripad Bhat solution, which bounce the tab at the end of the slide.
Here's my workaround...
Changes to onPageScrolled
method:
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
int tabStripChildCount = mTabStrip.getChildCount();
if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {
return;
}
mTabStrip.onViewPagerPageChanged(position, positionOffset);
View selectedTitle = mTabStrip.getChildAt(position);
int selectedOffset = (selectedTitle == null) ? 0 : selectedTitle.getWidth();
int nextTitlePosition = position + 1;
View nextTitle = mTabStrip.getChildAt(nextTitlePosition);
int nextOffset = (nextTitle == null) ? 0 : nextTitle.getWidth();
int extraOffset = (int)(0.5F * (positionOffset * (float)(selectedOffset + nextOffset)));
scrollToTab(position, extraOffset);
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
}
Changes to scrollToTab
method:
private int mLastScrollTo;
private void scrollToTab(int tabIndex, int positionOffset) {
final int tabStripChildCount = mTabStrip.getChildCount();
if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {
return;
}
View selectedChild = mTabStrip.getChildAt(tabIndex);
if (selectedChild != null && selectedChild.getMeasuredWidth() != 0) {
int targetScrollX = ((positionOffset + selectedChild.getLeft()) - getWidth() / 2) + selectedChild.getWidth() / 2;
if (targetScrollX != mLastScrollTo) {
scrollTo(targetScrollX, 0);
mLastScrollTo = targetScrollX;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With