如何使ViewPager循环?ViewPager

2023-09-12 22:49:28 作者:时间的流逝

我有一些意见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;
}

不过,我得到一个错误

But I got an error

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

你能帮助我吗?

Can you help me please?

感谢

推荐答案

一种可能性是建立这样的画面:

One possibility is setting up the screens like this:

C'A B C A

C' A B C A'

C'看起来就像C,但是当你滚动到那里,它可以切换到真正的C. 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像这样:

@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并通过引起跳跃瞬间发生,而不是一个平滑滚动。

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.

还要注意的是,因为该视图寻呼机不让点击通过对基础控制后才滚动已解决,它可能是罚款,没有设置clicklisteners之类的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.

编辑:现在既然已经实现了这个我自己,还有另外一个pretty的主要缺点。当它从一个交换机的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.

 
精彩推荐