有时候在做列表显示时,需要给列表中的listView添加动画。在我做过的项目中大多数都是每个Item的上浮动画,动画比较简单,直接上代码。
AnimationSet animationSet = new AnimationSet(false);
animationSet.setDuration(duration);
if (listener != null) {
animationSet.setAnimationListener(listener);
}
animationSet.setFillBefore(true);
animationSet.setStartOffset(startOffset);
Animation translateAnimation = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0,
Animation.RELATIVE_TO_SELF, 0,
Animation.ABSOLUTE, DrawUtils.dip2px(context, 100),
Animation.RELATIVE_TO_SELF, 0);
translateAnimation.setInterpolator(interpolator);
animationSet.addAnimation(translateAnimation);
Animation alphaAnimation = new AlphaAnimation(0, 1);
animationSet.addAnimation(alphaAnimation);
很简单的补间动画,一个向上平移100pix的平移动画和从不显示到显示的的Alpha动画。
使用:要想让ListView中的每个Item都展示动画,那么我们需要在getView方法里,为convertView设置并启动Animation,即convertView.startAnimation(animation)。
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//////////动画///////////////
if (convertView != null) {
AnimationSet animationSet = new AnimationSet(false);
animationSet.setDuration(mAnimDuration);
animationSet.setAnimationListener(this);
animationSet.setFillBefore(true);
animationSet.setStartOffset(mCurrentAnimationCount * mAnimDuration / 3);
Animation translateAnimation = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0,
Animation.RELATIVE_TO_SELF, 0,
Animation.ABSOLUTE, dip2px(mContext, 100),
Animation.RELATIVE_TO_SELF, 0);
translateAnimation.setInterpolator(mInterpolator);
animationSet.addAnimation(translateAnimation);
Animation alphaAnimation = new AlphaAnimation(0, 1);
animationSet.addAnimation(alphaAnimation);
convertView.startAnimation(animationSet);
++mCurrentAnimationCount;
HANDLER.post(mRunnable);
}
///////////结束//////////////////////////////
return convertView;
}
这样同时也存在一个问题,就是getView滚动的时候会造成Item之间进行联动。因此,可以添加一个标志位来控制:
if (convertView != null
&& position > mPreviousPostition) {
mPreviousPostition = position; // 初始值为-1
AnimationSet animationSet = new AnimationSet(false);
animationSet.setDuration(mAnimDuration);
animationSet.setAnimationListener(this);
animationSet.setFillBefore(true);
animationSet.setStartOffset(mCurrentAnimationCount * mAnimDuration / 3);
Animation translateAnimation = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0,
Animation.RELATIVE_TO_SELF, 0,
Animation.ABSOLUTE, dip2px(mContext, 100),
Animation.RELATIVE_TO_SELF, 0);
translateAnimation.setInterpolator(mInterpolator);
animationSet.addAnimation(translateAnimation);
Animation alphaAnimation = new AlphaAnimation(0, 1);
animationSet.addAnimation(alphaAnimation);
convertView.startAnimation(animationSet);
++mCurrentAnimationCount;
HANDLER.post(mRunnable);
}
///////////结束//////////////////////////////
return convertView;
}
这样ListView中每个Item的上浮动画就搞定了。