绚酷的ViewPager动画
参考自原文Great animations with PageTransformer。 以前的对ViewPager
动画只是停留在整个Pager切换的动画。例如这个JazzyViewPager库,把各种专场动画做的非常绚丽。其实,利用ViewPager
还有更迷人的动画效果。例如雅虎的News Digest应用的开场动画:
滑动翻页的同时,里面的View也分别也做各种动画。 实现的方法就是利用ViewPager.PageTransformer
。作者实现了一个简单的例子,先看效果:
实现方法就是:
mPager.setPageTransformer(false, new ViewPager.PageTransformer() {
@Override
public void transformPage(View view, float position) {
....
}
});
其中transformPage()
的实现如下:
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 <= 1) { // [-1,1]
mBlur.setTranslationX((float) (-(1 - position) * 0.5 * pageWidth));
mBlurLabel.setTranslationX((float) (-(1 - position) * 0.5 * pageWidth));
mDim.setTranslationX((float) (-(1 - position) * pageWidth));
mDimLabel.setTranslationX((float) (-(1 - position) * pageWidth));
mCheck.setTranslationX((float) (-(1 - position) * 1.5 * pageWidth));
mDoneButton.setTranslationX((float) (-(1 - position) * 1.7 * pageWidth));
// The 0.5, 1.5, 1.7 values you see here are what makes the view move in a different speed.
// The bigger the number, the faster the view will translate.
// The result float is preceded by a minus because the views travel in the opposite direction of the movement.
mFirstColor.setTranslationX((position) * (pageWidth / 4));
mSecondColor.setTranslationX((position) * (pageWidth / 1));
mTint.setTranslationX((position) * (pageWidth / 2));
mDesaturate.setTranslationX((position) * (pageWidth / 1));
// This is another way to do it
} else { // (1,+Infinity]
// This page is way off-screen to the right.
view.setAlpha(0);
}
}
还有雅虎的天气App如下效果:
其实现方法就非常简单了,如下:
public class ParallaxPageTransformer implements ViewPager.PageTransformer {
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(1);
} else if (position <= 1) { // [-1,1]
dummyImageView.setTranslationX(-position * (pageWidth / 2)); //Half the normal speed
} else { // (1,+Infinity]
// This page is way off-screen to the right.
view.setAlpha(1);
}
}
}
雅虎的很多App中用到了这种技术,看来已经被他们的工程师玩的炉火纯青了。