实现ViewPager的滑动翻页效果可以使用ViewPager的setPageTransformer方法,如下:
import android.content.Context; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.View; public class ReadViewPager extends ViewPager { public ReadViewPager(Context context) { super(context); } public ReadViewPager(Context context, AttributeSet attrs) { super(context, attrs); setAnima(); } public void setAnima() { setPageTransformer(true, new PageTransformer() { private static final float MIN_SCALE = 0.75f; @Override public void transformPage(View view, float position) { int pageWidth = view.getWidth(); int pageHeight =view.getHeight(); 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.setAlpha(1); 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); } } }); } }
核心代码是android官方demo,以上实现的是翻页效果是:上面一页被滑出界面时,下面一页慢慢显现,透明度慢慢加大,并且大小由小慢慢变大。
不过有一个奇怪的现象,当我做一个答题界面时,刚刚开始我采用ViewPager与View结合实现无限循环切换,并且采用上面的动画效果,可是每当我滑动到最后一张,也就是要开始新的一轮循环的时候,被滑出去的一页也会出现慢慢变透明的情况,而我用ViewPager结合Fragment实现无限循环切换的是就不会出现这种效果
如果想要实现仿造驾考宝典的翻页效果,只要把核心方法改为以下代码便可以了
setPageTransformer(true, new PageTransformer() { private static final float MIN_SCALE = 0.75f; @Override public void transformPage(View view, float position) { int pageWidth = view.getWidth(); int pageHeight =view.getHeight(); 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.setAlpha(1); 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); } } });
下面我们来讲讲position参数:
position的可能性的值有:
[-Infinity,-1) 已经看不到了
(1,+Infinity] 已经看不到了
[-1,1]
重点看[-1,1]这个区间 , 其他两个的View都已经看不到了~~
假设现在ViewPager在A页现在滑出B页,则:
A页的position变化就是( 0, -1]
B页的position变化就是[ 1 , 0 ]
参考博客:http://blog.csdn.net/lmj623565791/article/details/40411921
http://www.jianshu.com/p/251592d3ec62