[Tutorial] ViewPagerTransforms - Animations for transforming ViewPager on Android Studio

Welcome!

In this post, I’ll show you how to use ViewPagerTransforms Library to add some beautiful animations for transforming ViewPager on your Androids apps.

I - About Android Tutorials

I’ll be creating a big number of Android tutorials, showing you how to use nice libraries, UI, tips, and more.

I’ll be using Android Studio and Gradle in all tutorials.

If you need some help with any Android lib or feature, feel free to comment here and if possible, I can write a new tutorial about it :)

Source Codes:

Get updates Follow @aron-bordin
Star it: Star
Contribute: Fork
Download: Download

II - ViewPagerTransforms UI Library

Library containing common animations needed for transforming ViewPager scrolling on Android v13+.

This library is a rewrite of the JazzyViewPager library and owes credit of the animation concepts directly to its source.

The purpose of this rewrite is to provide an easier to use and extend implementation of ViewPager animations.

This library is really simple to use. You’ll be able to add nice animations to the default android ViewPager.

III - Creating a new project

Now, let’s start to work with it. Start a new Android Studio project. And make sure to be using Android v13+ to be able to use this library. C

Create your app with a Blank Activity, called MainActivity.

Now, to add ViewPagerTransforms as a Gradle dependency, click on app, and with the right click of mouse, go to Open Module Settings(F4)

Open the Dependencies tab, click on the plus button and Library Dependency. Now add the following line to the search input and get the last version of this lib.

com.ToxicBakery.viewpager.transforms:view-pager-transforms

Click Ok and wait the Gradle Sync to finish. Now, just to make sure that your app is working, click in the run button.

IV - Layout files

Now, let’s edit our layout files. The first step is to create a layout to each slide. To make this tutorial simple, we are going to use the same layout file to all slides.

Create a simple xml file inside layout folder with the name slide_page.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="This is slide 1"
        android:id="@+id/textView"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

Now, just add a ViewPager to your activity_main:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.v4.view.ViewPager
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

V - Coding it

Now, it’s time to code our application :)

Open you MainActivity.java and remove some codes, keep it simple, like this one:

package com.wordpress.bytedebugger.viewpagertransforms;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import com.ToxicBakery.viewpager.transforms.RotateDownTransformer;


public class MainActivity extends FragmentActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
  }
}

Add some variables to work with the Android ViewPager:

    /**
     * The number of pages (wizard steps) to show in this demo.
     */
    private static final int NUM_PAGES = 100;

    /**
     * The pager widget, which handles animation and allows swiping horizontally to access previous
     * and next wizard steps.
     */
    private ViewPager mPager;

    /**
     * The pager adapter, which provides the pages to the view pager widget.
     */
    private PagerAdapter mPagerAdapter;


    private int selectedPage; // set selected page

Now, add the following code on OnCreate method:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Instantiate a ViewPager and a PagerAdapter.
        mPager = (ViewPager) findViewById(R.id.pager); //the UI pager
        mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
        mPager.setAdapter(mPagerAdapter);
            mPager.setPageTransformer(true, new RotateDownTransformer()); //set the animation

        selectedPage = 0; //current page
        if(savedInstanceState != null){ //if app was paused, you can reopen the same page
            selectedPage = savedInstanceState.getInt("SELECTED_PAGE");
        }

        mPager.setCurrentItem(selectedPage); //set the current page
    }

You can see a list with all available animation here: https://github.com/ToxicBakery/ViewPagerTransforms/tree/master/library/src/main/java/com/ToxicBakery/viewpager/transforms

Add the following method to handle back button click:

    @Override
    public void onBackPressed() {
        if (mPager.getCurrentItem() == 0) {
            // If the user is currently looking at the first step, allow the system to handle the
            // Back button. This calls finish() on this activity and pops the back stack.
            super.onBackPressed();
        } else {
            // Otherwise, select the previous step.
            mPager.setCurrentItem(mPager.getCurrentItem() - 1);
        }
    }

To get a page_slide.xml and show it, it’s necessary to handle it with a Fragment. So, inside your main MainActivity class, the this new class:

    /**
     * A simple pager adapter that represents all ScreenSlidePageFragment objects, in
     * sequence.
     */
    private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
        public ScreenSlidePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            final Bundle bundle = new Bundle();
            bundle.putInt(SlideFragment.EXTRA_POSITION, position);
            final SlideFragment fragment = new SlideFragment();
            fragment.setArguments(bundle);

            return fragment;
        }

        @Override
        public int getCount() {
            return NUM_PAGES;
        }
    }

Create a new public class, SlideFragment.java. This class will handle each new page and show it.

package com.wordpress.bytedebugger.viewpagertransforms;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.Random;


public class SlideFragment extends Fragment {
    public static final String EXTRA_POSITION = "EXTRA_POSITION";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup) inflater.inflate(
                R.layout.slide_page, container, false);

        int position = getArguments().getInt(EXTRA_POSITION);
        TextView txt = (TextView)rootView.findViewById(R.id.textView);
        txt.setText("This is slide " + position); //edit the view text


        //set a random color to the background
        Random rnd = new Random();
        int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
        rootView.setBackgroundColor(color); //set a random color to the background

        return rootView; //return the slide view
    }
}

Now, you can run and test your app :)

Feel free to test all animations and choose the best one to your app. You just need to edit the following line:

mPager.setPageTransformer(true, new RotateDownTransformer()); //set the animation

That’s it, thanks for reading!

Aron Bordin

Aron Bordin

Aron Bordin
Computer Science Student and AI researcher. Always coding something fun :)

[Tutorial] Developing Android Background Services

### Welcome!In this post, I'll show you how to develop background services on Android Studio. We'll see two type of services: `Service` a...… Continue reading