主要是通过AnimatorUpdateListener获得状态,运行一个不现实的动画,根据获得的运行值自己设置view或者drawable的状态。
代码如下
ValueAnimator alphaAnim = null;
/**
* 透明渐变的动画
* @param animType 动画的类型,循环/单次 0是单次,1是循环,默认0
* @param drawable 结束之后的前景
**/
public void startAlphaAnim(final int animType,final int overDrawable){
alphaAnim =ObjectAnimator.ofInt(255,0);
alphaAnim.setDuration(2000);
if(1==animType){
alphaAnim.setRepeatCount(-1);
alphaAnim.setRepeatMode(ValueAnimator.REVERSE);
}
alphaAnim.addUpdateListener(new AnimatorUpdateListener(){
@Override
public void onAnimationUpdate(ValueAnimator animation) {
int frameValue = (Integer) animation.getAnimatedValue();
getBackground().setAlpha(255-frameValue);
getDrawable().setAlpha(frameValue);
}
});
alphaAnim.addListener(new AnimatorListener(){
@Override
public void onAnimationStart(Animator animation) {}
@Override
public void onAnimationEnd(Animator animation) {
//将透明度的恢复放在前面,只有这样才是对同一对象入手
//背景色不需要做处理,因为背景色只有在动画的时候才有用
getDrawable().setAlpha(255);
setBackgroundColor(getResources().getColor(R.color.transparent));
setImageResource(overDrawable);
}
@Override
public void onAnimationCancel(Animator animation) {
//将透明度的恢复放在前面,只有这样才是对同一对象入手
//背景色不需要做处理,因为背景色只有在动画的时候才有用
getDrawable().setAlpha(255);
setBackgroundColor(getResources().getColor(R.color.transparent));
setImageResource(overDrawable);
}
@Override
public void onAnimationRepeat(Animator animation) {}
});
alphaAnim.start();
}
/**
* 取消渐变动画
**/
public void closeAlphaAnim(){
if(alphaAnim==null)
return;
alphaAnim.cancel();
alphaAnim = null;
}