In recent days, there are netizens in the group to ask: have you ever done ViewPager vertical sliding effect. In fact, this problem is very simple, the following is a simple implementation steps:

Let’s take a look at this image :(you’ll notice that switching the ViewPager a little slower will give you a color transition effect, so beautiful)

First, write a class inheriting ViewPager, set the viewPage toggle animation in the constructor, and override onInterceptTouchEvent to check whether the event is handled.

Create a class that inherits ViewPager as follows :(the MarkDown syntax is not highlighted well enough, so the rest is mapped)

public class MyViewPager extends ViewPager { public MyViewPager(Context context) { this(context, null); } public MyViewPager(Context context, AttributeSet attrs) { super(context, attrs); // Set the viewPage toggle animation, where the vertical sliding viewpager is actually implementedsetPageTransformer(true, new DefaultTransformer()); } @override public Boolean onInterceptTouchEvent(MotionEvent ev) {booleanIntercept = super.onInterceptTouchEvent(swapEvent(ev)); swapEvent(ev);return intercept;
	}

	@Override
	public boolean onTouchEvent(MotionEvent ev) {
	    returnsuper.onTouchEvent(swapEvent(ev)); } private MotionEvent swapEvent(MotionEvent event) {// Get the width and heightfloat width = getWidth();
		floatheight = getHeight(); // Convert the Y-axis distance to the X-axis distancefloatswappedX = (event.getY() / height) * width; // Convert the X-axis movement distance to the Y-axis movement distancefloatswappedY = (event.getX() / width) * height; Event.setlocation (swappedX,swappedY);returnevent; } // There is more code below... }Copy the code

Let’s look at the core class PageTransformer, which handles animation switches and the like. Below I define a custom PageTransformer that overwrites the transformPage method to handle animation switching direction.

The complete code is shown below:

Second, the method of use is also very simple.

Here is the code for MainActivity:

Here is the code for the PagerAdapter:

The complete MainActivity is shown below:

Iii. Layout files are as follows:

So view_one.xml, view_two, view_three, same thing, just different text. To keep it simple, I’m just using TextView.

ViewPager loads the layout content

The code for activity_main.xml looks like this: