如何制作 ViewPager 循环? [英] How to make a ViewPager loop?

查看:19
本文介绍了如何制作 ViewPager 循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有一些视图的 ViewPager.我想在最后一个向右滑动后转到第一个.

I have a ViewPager with some views. I'd like to go to the first one after right swiping on the last one.

我试过了

@Override
public Fragment getItem(int arg0) {
    int i = arg0 % fragmentList.size();
    return fragmentList.get(i);
}

@Override
public int getCount() {
    return fragmentList.size()+1;
}

但是我遇到了一个错误

E/AndroidRuntime(22912): java.lang.IllegalStateException: Fragment already added: RubricFragment{4136cd80 #1 id=0x7f06000c android:switcher:2131099660:0}

推荐答案

一种可能性是像这样设置屏幕:

One possibility is setting up the screens like this:

C' A B C A'

C' A B C A'

C' 看起来很像 C,但是当您滚动到那里时,它会将您切换到真正的 C.A' 看起来就像 A,但是当您滚动到那里时,它会将您切换到真正的 A.

C' looks just like C, but when you scroll to there, it switches you to the real C. A' looks just like A, but when you scroll to there, it switches you to the real A.

我会通过实施 onPageScrollStateChanged 像这样:

I would do this by implementing onPageScrollStateChanged like so:

@Override
public void onPageScrollStateChanged (int state) {
    if (state == ViewPager.SCROLL_STATE_IDLE) {
        int curr = viewPager.getCurrentItem();
        int lastReal = viewPager.getAdapter().getCount() - 2;
        if (curr == 0) {
            viewPager.setCurrentItem(lastReal, false);
        } else if (curr > lastReal) {
            viewPager.setCurrentItem(1, false);
        }
    }
}

请注意,这调用了 的替代形式setCurrentItem 并传递 false 使跳转立即发生,而不是平滑滚动.

Note that this calls the alternate form of setCurrentItem and passes false to cause the jump to happen instantly rather than as a smooth scroll.

我认为这有两个主要缺点.首先,在到达任一端时,用户必须让滚动稳定下来,然后才能继续前进.其次,这意味着拥有第一页和最后一页中所有视图的第二个副本.根据您的屏幕资源占用的程度,这可能会排除此技术作为可能的解决方案.

There are two main drawbacks I see to this. Firstly, upon reaching either end the user has to let the scrolling settle before they can go further. Secondly, it means having a second copy of all of the views in your first and last page. Depending on how resource-heavy your screens are, that may rule out this technique as a possible solution.

另请注意,由于视图分页器在滚动稳定之前不会让点击进入底层控件,因此最好不要为 A' 和 C' 片段设置点击监听器等.

Note also that since the view pager doesn't let clicks go through to underlying controls until after the scrolling has settled, it's probably fine to not set up clicklisteners and the like for the A' and C' fragments.

现在自己实现了这个,还有另一个非常大的缺点.当它从 A' 切换到 A 或 C' 到 C 时,屏幕会闪烁片刻,至少在我当前的测试设备上是这样.

Having now implemented this myself, there's another pretty major drawback. When it switches from A' to A or C' to C, the screen flickers for a moment, at least on my current test device.

这篇关于如何制作 ViewPager 循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆