Wilbert Tan
Wilbert Tan

Reputation: 21

Snapchat-like Viewpager Animation

I'm trying to create an animation just like the Snapchat Viewpager, where the background of the left and right fragments are faded in but the contents are sliding in. All these happens while the camera fragment (centre fragment) stays static. It's like the left and right fragments are overlapping the centre fragment.

I've seen multiple tutorials, and the closest I could find is this link : OnPageChangeListener alpha crossfading

The problem with this is that it only works only when the right fragment comes in view. While the left fragment's background doesn't overlap the centre fragment.

CODE :

public class CustomPageTransformer implements ViewPager.PageTransformer {
public void transformPage(View view, float position) {
    int pageWidth = view.getWidth();
    View imageView = view.findViewById(R.id.image_view);
    View contentView = view.findViewById(R.id.content_area);

    if (position < -1) { // [-Infinity,-1)
        // This page is way off-screen to the left
    } else if (position <= 0) { // [-1,0]
        // This page is moving out to the left

        // Counteract the default swipe
        view.setTranslationX(pageWidth * -position);
        if (contentView != null) {
            // But swipe the contentView
            contentView.setTranslationX(pageWidth * position);
        }
        if (imageView != null) {
            // Fade the image in
            imageView.setAlpha(1 + position);
        }

    } else if (position <= 1) { // (0,1]
        // This page is moving in from the right

        // Counteract the default swipe
        view.setTranslationX(pageWidth * -position);
        if (contentView != null) {
            // But swipe the contentView
            contentView.setTranslationX(pageWidth * position);
        }
        if (imageView != null) {
            // Fade the image out
            imageView.setAlpha(1 - position);
        }
    } else { // (1,+Infinity]
        // This page is way off-screen to the right
    }
}

Example :

Official Snapchat App

Example above shows that the camera is static (non-moving), while the background of the discover page is overlapping the camera fragment (centre fragment), but the contents of the discover page is sliding in (also overlapping the camera fragment)

If any of you guys have any idea on how to do this, I would really appreciate this.

Upvotes: 2

Views: 505

Answers (1)

Asad Mukhtar
Asad Mukhtar

Reputation: 461

You can use this library to implement the same UI as SnapChat. This library also provide customization like showing more then 3 tab and also have alot of features that helps you to build Snap Like Viewpager.

SnapTabLayout

enter image description here

enter image description here

Upvotes: 2

Related Questions