Android 实现个性的ViewPager切换动画 实战PageTransformer(兼容Android3.0下面)

转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/40411921。本文出自:【张鸿洋的博客】

1、概述

之前写过一篇博文:Android 自己定义 ViewPager 打造千变万化的图片切换效果有兄弟提出。ViewPager自带了一个setPageTransformer用于设置切换动画~

本篇博文,将:

1、介绍怎样使用setPageTransformer设置切换动画;

2、自己定义PageTransformer实现个性的切换动画;

3、该方法在SDK11下面的版本号不起作用。我们会对其做一定改动,让其向下兼容。

官方演示样例地址:http://developer.android.com/training/animation/screen-slide.html 有兴趣的能够去看看~~


好了,下面開始编写代码~~

2、setPageTransformer的使用

首先我们迅速的实现一个传统的ViewPager效果~

1、布局文件

<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" >

    <android.support.v4.view.ViewPager
        android:id="@+id/id_viewpager"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</RelativeLayout>

2、MainActivity

package com.zhy.demo_zhy_08_viewpageranim;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

public class MainActivity extends Activity
{
	private ViewPager mViewPager;
	private int[] mImgIds = new int[] { R.drawable.guide_image1,
			R.drawable.guide_image2, R.drawable.guide_image3 };
	private List<ImageView> mImageViews = new ArrayList<ImageView>();

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);

		initData();

		mViewPager = (ViewPager) findViewById(R.id.id_viewpager);

		mViewPager.setAdapter(new PagerAdapter()
		{
			@Override
			public Object instantiateItem(ViewGroup container, int position)
			{

				container.addView(mImageViews.get(position));
				return mImageViews.get(position);
			}

			@Override
			public void destroyItem(ViewGroup container, int position,
					Object object)
			{

				container.removeView(mImageViews.get(position));
			}

			@Override
			public boolean isViewFromObject(View view, Object object)
			{
				return view == object;
			}

			@Override
			public int getCount()
			{
				return mImgIds.length;
			}
		});

	}

	private void initData()
	{
		for (int imgId : mImgIds)
		{
			ImageView imageView = new ImageView(getApplicationContext());
			imageView.setScaleType(ScaleType.CENTER_CROP);
			imageView.setImageResource(imgId);
			mImageViews.add(imageView);
		}
	}

}

好了。这样一个传统ViewPager就实现了~~大家对上面代码应该不会有不论什么陌生的感觉~执行效果也不用贴图了。大家肯定知道~~

3、PageTransformer

ViewPager有个方法叫做:

setPageTransformer(boolean reverseDrawingOrder, PageTransformer transformer) 用于设置ViewPager切换时的动画效果。而且google官方还给出了两个演示样例。

仅仅须要在上述代码中调用setPageTransformer就可以加入切换动画效果~~下面演示google的两个PageTransformer的代码,以及执行效果。

1、DepthPageTransformer

public class DepthPageTransformer implements ViewPager.PageTransformer {
    private static final float MIN_SCALE = 0.75f;

    public void transformPage(View view, float position) {
        int pageWidth = view.getWidth();

        if (position < -1) { // [-Infinity,-1)
            // This page is way off-screen to the left.
            view.setAlpha(0);

        } else if (position <= 0) { // [-1,0]
            // Use the default slide transition when moving to the left page
            view.setAlpha(1);
            view.setTranslationX(0);
            view.setScaleX(1);
            view.setScaleY(1);

        } else if (position <= 1) { // (0,1]
            // Fade the page out.
            view.setAlpha(1 - position);

            // Counteract the default slide transition
            view.setTranslationX(pageWidth * -position);

            // Scale the page down (between MIN_SCALE and 1)
            float scaleFactor = MIN_SCALE
                    + (1 - MIN_SCALE) * (1 - Math.abs(position));
            view.setScaleX(scaleFactor);
            view.setScaleY(scaleFactor);

        } else { // (1,+Infinity]
            // This page is way off-screen to the right.
            view.setAlpha(0);
        }
    }
}

调用代码:

mViewPager.setPageTransformer(true, new DepthPageTransformer());

效果:


2、ZoomOutPageTransformer

package com.zhy.view;

import android.annotation.SuppressLint;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;

public class ZoomOutPageTransformer implements ViewPager.PageTransformer
{
	private static final float MIN_SCALE = 0.85f;
	private static final float MIN_ALPHA = 0.5f;

	@SuppressLint("NewApi")
	public void transformPage(View view, float position)
	{
		int pageWidth = view.getWidth();
		int pageHeight = view.getHeight();

		Log.e("TAG", view + " , " + position + "");

		if (position < -1)
		{ // [-Infinity,-1)
			// This page is way off-screen to the left.
			view.setAlpha(0);

		} else if (position <= 1) //a页滑动至b页 ; a页从 0.0 -1 ;b页从1 ~ 0.0
		{ // [-1,1]
			// Modify the default slide transition to shrink the page as well
			float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position));
			float vertMargin = pageHeight * (1 - scaleFactor) / 2;
			float horzMargin = pageWidth * (1 - scaleFactor) / 2;
			if (position < 0)
			{
				view.setTranslationX(horzMargin - vertMargin / 2);
			} else
			{
				view.setTranslationX(-horzMargin + vertMargin / 2);
			}

			// Scale the page down (between MIN_SCALE and 1)
			view.setScaleX(scaleFactor);
			view.setScaleY(scaleFactor);

			// Fade the page relative to its size.
			view.setAlpha(MIN_ALPHA + (scaleFactor - MIN_SCALE)
					/ (1 - MIN_SCALE) * (1 - MIN_ALPHA));

		} else
		{ // (1,+Infinity]
			// This page is way off-screen to the right.
			view.setAlpha(0);
		}
	}
}

调用代码:

mViewPager.setPageTransformer(true, new ZoomOutPageTransformer());

效果:



效果图都是google官网上的,我们的測试图会在兼容3.0下面贴出来。不然就反复了~~

为ViewPager加入切换就一行代码是不是非常happy,可惜是不兼容3.0下面的版本号的。该方法的凝视上写到:

setting a PageTransformer prior to Android 3.0 (API 11) will have no effect 在3.0之前的版本号设置此方法是没有效果的,那么下面我们就看怎样让其兼容3.0下面版本号。

3、版本号的向下兼容

1、不兼容的原因

首先看下为什么不兼容,3.0下面呢?

看上面的两个演示样例代码,代码中View的动画使用的是属性动画,而属性动画是3.0才推出的。那么这么写肯定是不兼容3.0下面了~

那么我们首先引入nineoldandroids。让动画先能在3.0下面跑再说:

改动DepthPageTransformer

package com.zhy.view;

import com.nineoldandroids.view.ViewHelper;

import android.annotation.SuppressLint;
import android.support.v4.view.ViewPager;
import android.view.View;

public class DepthPageTransformer implements ViewPager.PageTransformer
{
	private static final float MIN_SCALE = 0.75f;

	public void transformPage(View view, float position)
	{
		int pageWidth = view.getWidth();

		if (position < -1)
		{ // [-Infinity,-1)
			// This page is way off-screen to the left.
			// view.setAlpha(0);
			ViewHelper.setAlpha(view, 0);
		} else if (position <= 0)// a页滑动至b页 ; a页从 0.0 -1 ;b页从1 ~ 0.0
		{ // [-1,0]
			// Use the default slide transition when moving to the left page
			// view.setAlpha(1);
			ViewHelper.setAlpha(view, 1);
			// view.setTranslationX(0);
			ViewHelper.setTranslationX(view, 0);
			// view.setScaleX(1);
			ViewHelper.setScaleX(view, 1);
			// view.setScaleY(1);
			ViewHelper.setScaleY(view, 1);

		} else if (position <= 1)
		{ // (0,1]
			// Fade the page out.
			// view.setAlpha(1 - position);
			ViewHelper.setAlpha(view, 1 - position);

			// Counteract the default slide transition
			// view.setTranslationX(pageWidth * -position);
			ViewHelper.setTranslationX(view, pageWidth * -position);

			// Scale the page down (between MIN_SCALE and 1)
			float scaleFactor = MIN_SCALE + (1 - MIN_SCALE) * (1 - position);
			// view.setScaleX(scaleFactor);
			ViewHelper.setScaleX(view, scaleFactor);
			// view.setScaleY(1);
			ViewHelper.setScaleY(view, scaleFactor);

		} else
		{ // (1,+Infinity]
			// This page is way off-screen to the right.
			// view.setAlpha(0);
			ViewHelper.setAlpha(view, 1);
		}
	}
}

非常easy,把全部属性动画换成ViewHelper去设置就好了。如今我们去3.0下面的机子上去执行。发现还是没有效果~~~

为什么呢?

我们再去看看setPageTransformer的源代码:

 public void setPageTransformer(boolean reverseDrawingOrder, PageTransformer transformer) {
        if (Build.VERSION.SDK_INT >= 11) {
            final boolean hasTransformer = transformer != null;
            final boolean needsPopulate = hasTransformer != (mPageTransformer != null);
            mPageTransformer = transformer;
            setChildrenDrawingOrderEnabledCompat(hasTransformer);
            if (hasTransformer) {
                mDrawingOrder = reverseDrawingOrder ? DRAW_ORDER_REVERSE : DRAW_ORDER_FORWARD;
            } else {
                mDrawingOrder = DRAW_ORDER_DEFAULT;
            }
            if (needsPopulate) populate();
        }
    }

最终发现原因了。原来在此方法内部推断了假设是11以上的版本号才让动画生效~~

那么,没办法了,假设想兼容。必须改动ViewPager的源代码了~~

2、完美向下兼容

我们将ViewPager的源代码拷贝一份至我们的项目中。改动名称为ViewPagerCompat。然后凝视掉SDK版本号推断那一句

public class ViewPagerCompat extends ViewGroup {

public void setPageTransformer(boolean reverseDrawingOrder, ViewPager.PageTransformer transformer) {
//        if (Build.VERSION.SDK_INT >= 11) 
        {
            final boolean hasTransformer = transformer != null;
            final boolean needsPopulate = hasTransformer != (mPageTransformer != null);
            mPageTransformer = transformer;
            setChildrenDrawingOrderEnabledCompat(hasTransformer);
            if (hasTransformer) {
                mDrawingOrder = reverseDrawingOrder ? DRAW_ORDER_REVERSE : DRAW_ORDER_FORWARD;
            } else {
                mDrawingOrder = DRAW_ORDER_DEFAULT;
            }
            if (needsPopulate) populate();
        }
    }
...
}

注意,全部的PageTransformer使用ViewPager.PageTransformer

然后我们把项目中的ViewPager改为ViewPagerCompat;记得改动布局文件。以及MainActivity中的ViewPager为ViewPagerCompat

我们在2.3.3的模拟器上測试下效果:



能够看到,我们的切换动画完美的执行在2.3.3的机器上~~so happy ~~没有ViewPager源代码的童鞋不要紧。我会在文末的源代码下载中加入ViewPager源代码,让你能够尽情去測试~~

当然了。仅仅是兼容当然不能满足我们的好奇心。难道我们做到了兼容,还仅仅能使用Google给的演示样例动画么~~我们强大的创新呢~~下面带领大家分析setPageTransformer方法,然后设计一个个性的动画切换效果

4、自己定义PageTransformer实现个性切换动画

 public interface PageTransformer {
        /**
         * Apply a property transformation to the given page.
         *
         * @param page Apply the transformation to this page
         * @param position Position of page relative to the current front-and-center
         *                 position of the pager. 0 is front and center. 1 is one full
         *                 page position to the right, and -1 is one page position to the left.
         */
        public void transformPage(View page, float position);
    }

能够看到该接口仅仅有一个方法,第一个是我们的view,第二个是position~~

当我们滑动时:会打印出当然ViewPager中存活的每个View以及它们的position的变化~~注意是每个,所以建议别仅仅log position,不然你会认为莫名其妙的输出~~

position的可能性的值有,事实上从官方演示样例的凝视就能看出:

[-Infinity,-1)  已经看不到了

(1,+Infinity] 已经看不到了

 [-1,1] 

重点看[-1,1]这个区间 , 其它两个的View都已经看不到了~~


假设如今ViewPager在A页如今滑出B页,则:

A页的position变化就是( 0, -1]

B页的position变化就是[ 1 , 0 ]

知道了我们滑动时position的变化~~那么就開始设计我们的个性的切换效果。

官方给的样例,有变化透明度、偏移量、缩放的,我们准备来个不一样的。我们变化角度。即rotation;

大概的效果是这种:


下面我们分析代码:

我们设置View的旋转中心为:

ViewHelper.setPivotX(view, view.getMeasuredWidth() * 0.5f);
ViewHelper.setPivotY(view, view.getMeasuredHeight());

依旧是ViewPager在A页如今滑出B页

那么A页应当在滑动过程中0度到-20度的偏移,B页应当在滑动过程中+20度到0度的偏移

结合

A页的position变化就是( 0, -1]

B页的position变化就是[ 1 , 0 ]

那么旋转的角度即:mRot = (20 * position); A页 mRot :0 ,~ -20 ; B页 mRot :20 ~ 0  ;

瞬间认为好简单:

完整代码:

package com.zhy.view;

import com.nineoldandroids.view.ViewHelper;

import android.annotation.SuppressLint;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;

public class RotateDownPageTransformer implements ViewPager.PageTransformer
{
	
	private static final float ROT_MAX = 20.0f;
	private float mRot;
	

	
	public void transformPage(View view, float position)
	{

		Log.e("TAG", view + " , " + position + "");

		if (position < -1)
		{ // [-Infinity,-1)
			// This page is way off-screen to the left.
			ViewHelper.setRotation(view, 0);

		} else if (position <= 1) // a页滑动至b页 。 a页从 0.0 ~ -1 ;b页从1 ~ 0.0
		{ // [-1,1]
			// Modify the default slide transition to shrink the page as well
			if (position < 0)
			{

				mRot = (ROT_MAX * position);
				ViewHelper.setPivotX(view, view.getMeasuredWidth() * 0.5f);
				ViewHelper.setPivotY(view, view.getMeasuredHeight());
				ViewHelper.setRotation(view, mRot);
			} else
			{

				mRot = (ROT_MAX * position);
				ViewHelper.setPivotX(view, view.getMeasuredWidth() * 0.5f);
				ViewHelper.setPivotY(view, view.getMeasuredHeight());
				ViewHelper.setRotation(view, mRot);
			}

			// Scale the page down (between MIN_SCALE and 1)

			// Fade the page relative to its size.

		} else
		{ // (1,+Infinity]
			// This page is way off-screen to the right.
			ViewHelper.setRotation(view, 0);
		}
	}
}

你没看错。if else 里面代码是一样的,为了好理解特意没有合并到一起~~~

 

到此,我们从setPageTransformer使用,到改动ViewPager做到向下兼容。直至自己定义出个性的切换效果 都已经介绍完成~~

大家能够发挥自己的创造力,做出各种奇妙的动画效果,ok,就到这里。

假设你喜欢自己定义ViewPager来实现,请移步:Android 自己定义 ViewPager 打造千变万化的图片切换效果



源代码点击下载


---------------------------------------------------------------------------------------------------------


博主部分视频已经上线。假设你不喜欢枯燥的文本,请猛戳(初录,期待您的支持):

1、高仿微信5.2.1主界面及消息提醒

2、高仿QQ5.0側滑








posted on 2017-04-21 10:32  blfbuaa  阅读(221)  评论(0编辑  收藏  举报