Michael P
Michael P

Reputation: 245

How to create Android ViewPager swipe overshoot/bounce animation?

How can I create an animation similar to the stock android launcher animation applied to apps when you change homescreen pages.

Here's a gif: https://i.sstatic.net/Zh7qE.gif

As the page swipes, the icons slightly overshoot their mark, and settle back to the center. I don't see how I can do that with a PageTransformer and I can't find any resources to point me in the right direction.

Upvotes: 1

Views: 380

Answers (2)

According to @Shlomi, you can do this implementation:

        var currentPage = 0

        binding.viewPager.onPageChangeListener {
            val pixels = binding.vpBennefits.width / 8
            ValueAnimator.ofInt(
                0, if (currentPage < it)
                    pixels
                else
                    -pixels
            ).apply {
                duration = 200L
                interpolator = DecelerateInterpolator()
                repeatCount = 1
                repeatMode = ValueAnimator.REVERSE
                addUpdateListener {
                    binding.vpBennefits.scrollX = it.animatedValue as Int
                }
            }.start()

            currentPage = it
        }

By this way you can obtain the desired effect in both sides

Upvotes: 0

Shlomi Katriel
Shlomi Katriel

Reputation: 2403

I once created a one-time bounce animation:

val pixels = binding.pager.width / 8
ValueAnimator.ofInt(0, pixels).apply {
    duration = 200L
    interpolator = DecelerateInterpolator()
    repeatCount = 3
    repeatMode = ValueAnimator.REVERSE
    addUpdateListener {
        binding.pager.scrollX = it.animatedValue as Int
    }
}.start()

Use ofInt(0, pixels) for bouncing left or ofInt(0, -pixels) to bouncing right.

In my code I used a dragging distance of 1/8 of the view pager. Feel free to choose how much you want to bounce: val pixels = PIXELS_TO_DRAG

Finally, the repeatCount determines how many bounces - use 3 for 2 bounces, 5 for 3 bounces, 7 for 4 bounces etc.

You can fire this animation each time a pager transition end and tweak the parameters to get the desired behavior.

Enjoy, Hope it helps :)

Upvotes: 2

Related Questions