先放效果(仿造平行空间):
welcom.gif
思路是利用ViewPager的PageTransformer,对每个page中的item执行相应动画
代码语言:javascript复制public class WelcompagerTransformer implements ViewPager.PageTransformer, ViewPager.OnPageChangeListener {
private boolean pageChanged;
//当前page的index
private int mPageIndex;
/**
* 此方法是滑动的时候每一个页面View都会调用该方法
* page:当前的页面
* position:当前滑动的位置
* 视差效果:在View正常滑动的情况下,给当前View或者当前view里面的每一个子view来一个加速度
* 而且每一个加速度大小不一样。
*/
@Override
public void transformPage(@NonNull View page, float position) {
//背景
View bg_container = page.findViewById(R.id.bg_container);
final View bg1 = page.findViewById(R.id.imageView0);
final View bg2 = page.findViewById(R.id.imageView0_2);
final MyScrollView mscv = page.findViewById(R.id.mscv);
//背景颜色变化
int bg1_green = page.getContext().getResources().getColor(R.color.bg1_green);
int bg2_blue = page.getContext().getResources().getColor(R.color.bg2_blue);
int pageIndex = (int) page.getTag();
ArgbEvaluator evaluator = new ArgbEvaluator();
int color = bg1_green;
if (pageIndex == mPageIndex) {//因为所有page都会调用此方法,但我们只要判断当前页的颜色改变,加了个当前页变量来判断
switch (pageIndex) {
case 0:
color = (int) evaluator.evaluate(Math.abs(position), bg1_green, bg2_blue);
break;
case 1:
color = (int) evaluator.evaluate(Math.abs(position), bg2_blue, bg1_green);
break;
case 2:
color = (int) evaluator.evaluate(Math.abs(position), bg1_green, bg2_blue);
break;
default:
break;
}
//给整个ViewPager设置颜色,保证整体性
((View) page.getParent()).setBackgroundColor(color);
}
if (position == 0) {//切换到当前页
//pageChanged作用--解决问题:只有在切换页面的时候才展示平移动画,如果不判断则会只是移动一点点当前页面松开也会执行一次平移动画
if (pageChanged) {
bg1.setVisibility(View.VISIBLE);
bg2.setVisibility(View.VISIBLE);
ValueAnimator valueAnimator = ValueAnimator.ofFloat(1f);
valueAnimator.setDuration(400);
valueAnimator.setInterpolator(new LinearInterpolator());
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float fraction = animation.getAnimatedFraction();
bg2.setTranslationX(bg2.getWidth() * (1 - fraction));
bg1.setTranslationX(-bg1.getWidth() * fraction);
//手机聊天界面平移
mscv.smoothScrollTo((int) (mscv.getWidth() * fraction), 0);
}
});
valueAnimator.start();
pageChanged = false;
}
} else if (position > -1 && position < 1) {//手指滑动过程中,没有切换到其他page的中间状态,背景有一个旋转的效果
//设置锚点
bg_container.setPivotX(page.getWidth() / 2f);
bg_container.setPivotY(page.getHeight());
//旋转(-30度到30度范围)
bg_container.setRotation(position * 30);
} else if (position == -1 || position == 1) {//说明当前page被滑到了左边或者右边
bg2.setTranslationX(0);
bg1.setTranslationX(0);
mscv.smoothScrollTo(0, 0);
}
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
mPageIndex = position;
pageChanged = true;
}
@Override
public void onPageScrollStateChanged(int state) {
}
}