使用Animation实现组件闪烁

Animation可以实现组件的简单动画,例如:组件闪烁。实现步骤如下:

TestActivity.java

package com.xiboliya.demo;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;

public class TestActivity extends Activity {
    private ImageView imgCover;
    private Animation animation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_test);
        initView();
    }

    private void initView() {
        imgCover = findViewById(R.id.img_cover);
        imgCover.setTag("0");
        imgCover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 点击图片开始闪烁或停止闪烁
                updateCover();
            }
        });
    }

    private Animation getAnimation() {
        if (animation == null) {
            animation = new AlphaAnimation(1f, 0.5f); // 透明度从100%到50%
            animation.setDuration(500); // 渐变循环的间隔时间为500毫秒
            animation.setInterpolator(new LinearInterpolator()); // 设置动画速度为匀速
            animation.setRepeatCount(Animation.INFINITE); // 设置动画重复的次数,INFINITE代表永久循环
            animation.setRepeatMode(Animation.REVERSE); // 设置反方向执行
        }
        return animation;
    }

    private void updateCover() {
        if ("0".equals(imgCover.getTag())) {
            // 开始闪烁
            imgCover.startAnimation(getAnimation());
            imgCover.setTag("1");
        } else {
            // 停止闪烁
            imgCover.clearAnimation();
            imgCover.setTag("0");
        }
    }

}

你可能感兴趣的:(Android相关,动画,android,Animation)