How to create carousel ViewPager?

前端 未结 3 1546
梦毁少年i
梦毁少年i 2021-02-04 17:20

All I want to do is a horizontal carousel in Android.

If I have 3 screens A B and C then I want my ViewPager to allow me to move like A <-> B, B <-> C, C <->

3条回答
  •  天涯浪人
    2021-02-04 17:42

    (Cross-posting my answer from an identical StackOverflow question)

    One possibility is setting up the screens like this:

    C' A B 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.

    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);
            }
        }
    }
    

    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.

    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.

    Edit: 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.

提交回复
热议问题