通过ValueAnimator实现呼吸灯效果

本文介绍了一种使用ValueAnimator实现透明渐变动画的方法,并提供了详细的代码示例。通过AnimatorUpdateListener监听动画更新过程,调整View或Drawable的透明度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

主要是通过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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值