Android从3.0开始,就添加了很多动画,ViewPager当然也不例外,相对于非常平庸的默认切换动画,Google给我们展示了两个动画例子:DepthPageTransformer和ZoomOutPageTransformer,实际上我们也可以通过实现ViewPager.PageTransformer来做出完全不同的切换动画效果。关键是要理解transformPage(View view, float position)的参数。view理所当然就是滑动中的那个view,position这里是float类型,不是平时理解的int位置,而是当前滑动状态的一个表示,比如当滑动到正全屏时,position是0,而向左滑动,使得右边刚好有一部被进入屏幕时,position是1,如果前一页和下一页基本各在屏幕占一半时,前一页的position是-0.5,后一页的posiotn是0.5,所以根据position的值我们就可以自行设置需要的alpha,x/y信息。
下面,我们来看看Google官方提供的两种动画效果的代码,很简单,相信每个人看过之后,都能自己实现一种动画效果,
DepthPageTransformer:
[java] view plain copy
1. public class DepthPageTransformer implements PageTransformer {
2. private static float MIN_SCALE = 0.75f;
3.
4. @SuppressLint("NewApi")
5. @Override
6. public void transformPage(View view, float position) {
7. int pageWidth = view.getWidth();
8. if (position < -1) { // [-Infinity,-1)
9. // This page is way off-screen to the left.
10. 0);
11. else if (position <= 0) { // [-1,0]
12. // Use the default slide transition when
13. // moving to the left page
14. 1);
15. 0);
16. 1);
17. 1);
18. else if (position <= 1) { // (0,1]
19. // Fade the page out.
20. 1 - position);
21. // Counteract the default slide transition
22. view.setTranslationX(pageWidth * -position);
23. // Scale the page down (between MIN_SCALE and 1)
24. float scaleFactor = MIN_SCALE + (1 - MIN_SCALE)
25. 1 - Math.abs(position));
26. view.setScaleX(scaleFactor);
27. view.setScaleY(scaleFactor);
28. else { // (1,+Infinity]
29. // This page is way off-screen to the right.
30. 0);
31.
32. }
33. }
34.
35. }
ZoomOutPageTransformer:
[java]
view plain
copy
1. public class ZoomOutPageTransformer implements PageTransformer {
2. private static float MIN_SCALE = 0.85f;
3.
4. private static float MIN_ALPHA = 0.5f;
5.
6. @Override
7. public void transformPage(View view, float position) {
8. int pageWidth = view.getWidth();
9. int pageHeight = view.getHeight();
10.
11. if (position < -1) { // [-Infinity,-1)
12. // This page is way off-screen to the left.
13. 0);
14. else if (position <= 1) { // [-1,1]
15. // Modify the default slide transition to
16. // shrink the page as well
17. float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position));
18. float vertMargin = pageHeight * (1 - scaleFactor) / 2;
19. float horzMargin = pageWidth * (1 - scaleFactor) / 2;
20. if (position < 0) {
21. 2);
22. else {
23. 2);
24. }
25. // Scale the page down (between MIN_SCALE and 1)
26. view.setScaleX(scaleFactor);
27. view.setScaleY(scaleFactor);
28. // Fade the page relative to its size.
29. view.setAlpha(MIN_ALPHA + (scaleFactor - MIN_SCALE)
30. 1 - MIN_SCALE) * (1 - MIN_ALPHA));
31. else { // (1,+Infinity]
32. // This page is way off-screen to the right.
33. 0);
34. }
35. }
36. }
有了这两种效果,我们在代码中设置一下就生效了:mPager.setPageTransformer(true, new DepthPageTransformer());
下面是效果图:第一张是
DepthPageTransformer效果,第二张是ZoomOutPageTransformer效果。