如何在Android滑动选项卡布局中对齐活动选项卡中心

Shr*_*hat 8 android android-viewpager

我在android滑动标签布局+视图寻呼机中有12个项目.从左向右滑动时,所选标签应与播放商店中心相同.请帮我怎么做.在我的应用程序中,活动选项卡始终位于屏幕左侧.

在此输入图像描述

在此输入图像描述

Yur*_*upa 12

我的方法与Shripad Bhat解决方案略有不同,后者在幻灯片末尾弹出选项卡.

这是我的解决方法......

onPageScrolled方法的更改:

@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);
    }
}
Run Code Online (Sandbox Code Playgroud)

scrollToTab方法的更改:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你,真棒.但是如何在中心制作第一个标签项? (3认同)

Shr*_*hat 3

Google 提供了滑动选项卡布局的示例。但在SlidingTabLayout类的实现中,它并不是为选定的选项卡居中对齐而设计的。我修改了滚动方法以使所选/活动选项卡位于屏幕中心。这是代码更改:

类名:SlidingTabLayout

行号:241,scrollToTab{}

更新方法:

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) {
        int targetScrollX = selectedChild.getLeft() + positionOffset;

        if (tabIndex > 0 || positionOffset > 0) {
            // If we're not at the first child and are mid-scroll, make sure we obey the offset
            targetScrollX -= (getWidth()-selectedChild.getWidth())/2;
        }

        scrollTo(targetScrollX, 0);
    }
}
Run Code Online (Sandbox Code Playgroud)