这里写代码片
公司要求做在按钮上做一个呼吸灯的效果,想了一下,可以做一个北京,背景执行动画,让他循环的消失和出现,首先要做两个动画
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true"
android:fillEnabled="true" >
<alpha
android:duration="1500"
android:fromAlpha="0.0"
android:toAlpha="1.0" />
</set>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true"
android:fillEnabled="true" >
<alpha
android:duration="1500"
android:fromAlpha="1.0"
android:toAlpha="0.0" />
</set>
然后就是自己包装了一下的imageview
public class loopPicture extends ImageView{
private Context mContext;
private ImageView breathImageView;
private Timer timer;
private boolean isOpen = true;
private int index = 0;
private final int BREATH_INTERVAL_TIME = 1000; //设置呼吸灯时间间隔
public Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
breathImageView.clearAnimation();
breathImageView.setAnimation(getFadeIn());
break;
case 2:
breathImageView.clearAnimation();
breathImageView.setAnimation(getFadeOut());
break;
}
super.handleMessage(msg);
}
};
public loopPicture(Context context) {
super(context);
this.mContext=context;
breathImageView=this;
startTimer();
}
public loopPicture(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.mContext=context;
breathImageView=this;
startTimer();
}
public loopPicture(Context context, AttributeSet attrs) {
super(context, attrs);
this.mContext=context;
breathImageView=this;
startTimer();
}
private Animation getFadeIn() {
Animation fadeIn = AnimationUtils.loadAnimation(mContext,
R.anim.alpha_fade_in);
fadeIn.setDuration(BREATH_INTERVAL_TIME);
fadeIn.setStartOffset(100);
return fadeIn;
}
private Animation getFadeOut() {
Animation fadeOut = AnimationUtils.loadAnimation(mContext,
R.anim.alpha_fade_out);
fadeOut.setDuration(BREATH_INTERVAL_TIME);
fadeOut.setStartOffset(100);
return fadeOut;
}
private void startTimer() {
timer = new Timer(true);
TimerTask task = new TimerTask() {
@Override
public void run() {
if (isOpen) {
if (index == 2) {
index = 0;
}
index++;
Message message = new Message();
message.what = index;
handler.sendMessage(message);
}
}
};
timer.schedule(task, 0, BREATH_INTERVAL_TIME); // 延时0ms后执行,5000ms执行一次
}
}