观察上面的Gif图,当滑动ViewPager页时,底部的钢琴界面首先会进行一次位移,将ViewPager对应的底部Item移动到中心,之后将此Item升起,将之前的Item降下所以我们总共需要3个动画,一个滚动动画,一个升起动画,一个降下动画,而且在上图中可以看出动画的执行实在ViewPager切换后执行的所以我们需要设置它的OnPageChangeListener。在OnPageSelected方法中执行组合动画

在RhythmLayout中添加方法以供外部调用这个组合动画
/**
* 位移到所选中的item位置,并进行相应的动画
*
* @param position 被选中的item位置
*/
public void showRhythmAtPosition(int position) {
//如果所要移动的位置和上一次一样则退出方法
if (this.mLastDisplayItemPosition == position)
return;
//ScrollView的滚动条位移动画
Animator scrollAnimator;
//item的弹起动画
Animator bounceUpAnimator;
//item的降下动画
Animator shootDownAnimator;
if ((this.mLastDisplayItemPosition < 0) || (mAdapter.getCount() <= 7) || (position <= 3)) {
//当前要位移到的位置为前3个时或者总的item数量小于7个
scrollAnimator = scrollToPosition(0, mScrollStartDelayTime, false);
} else if (mAdapter.getCount() - position <= 3) {
//当前要位移到的位置为最后3个
scrollAnimator = scrollToPosition(mAdapter.getCount() - 7, mScrollStartDelayTime, false);
} else {
//当前位移到的位置既不是前3个也不是后3个
scrollAnimator = scrollToPosition(position - 3, mScrollStartDelayTime, false);
}
//获取对应item升起动画
bounceUpAnimator = bounceUpItem(position, false);
//获取对应item降下动画
shootDownAnimator = shootDownItem(mLastDisplayItemPosition, false);
//动画合集 弹起动画和降下动画的组合
AnimatorSet animatorSet1 = new AnimatorSet();
if (bounceUpAnimator != null) {
animatorSet1.playTogether(bounceUpAnimator);
}
if (shootDownAnimator != null) {
animatorSet1.playTogether(shootDownAnimator);
}
//3个动画的组合
AnimatorSet animatorSet2 = new AnimatorSet();
animatorSet2.playSequentially(new Animator[]{scrollAnimator, animatorSet1});
animatorSet2.start();
mLastDisplayItemPosition = position;
}
mLastDisplayItemPosition为上次选中的item的位置,mScrollStartDelayTime为动画延迟执行的时间,其他都有详细的注释,并不难理解scrollToPosition()方法中调用的是AnimatorUtils中的moveScrollViewToX()方法它将会移动ScrollView的x轴到指定的位置