给ViewPager 添加动画
v4 包中的ViewPager 提供了设置动画的API ,setPageTransformer();
viewPager的动画实例需要实现PageTransformer 接口;
/**
* A PageTransformer is invoked whenever a visible/attached page is scrolled.
* This offers an opportunity for the application to apply a custom transformation
* to the page views using animation properties.
*
* <p>As property animation is only supported as of Android 3.0 and forward,
* setting a PageTransformer on a ViewPager on earlier platform versions will
* be ignored.</p>
*/
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.
*/
void transformPage(@NonNull View page, float position);
}
PageTransformer 接口中的 transformPage()方法理解:
page 参数是viewpager 当前页面,因为会看到多个view,其和position 是一对一的关系。
position 参数,
1:假设当前viewpager 正常的展示,无任何滑动操作之类,那么page 就是当前看到的view, position 此时 为 0;
2:假设当前手指向左滑动,也就是要展示右边下一张view的内容,
那么当前手指滑动的那个view ,为之前正常看到的view, position 的值会是(-1, 0)中的某个值,要即将展示的view ,也有自己对应的position , 其值会是(0,1)中的某个值;
3:假设当前手指向右滑动,也就是要展示左边下一张view的内容,
那么当前手指滑动的那个view ,为之前正常看到的view, position 的值会是(0, 1)中的某个值,要即将展示的view ,也有自己对应的position , 其值会是(-1,0)中的某个值;
上述可能没说明白, 看看下面的例子 ,看是否能清晰些;
这里分析下 Google 提供的一个sample.
定义区间为 ( - 无穷,-1 ),( - 1,0 ] , ( 0 , 1] ,(1,无穷);
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 + position);
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);
}
}
}
上面的示例 在 (-1 ,0 ) ,(0 ,1) 直接是做了区分的,所以左右滑动会有差异,如果想做到左右对称,将两个区间合并为一个,定义区间改为 定义区间为 ( - 无穷,-1 ),[ - 1, 1] ,(1,无穷);