Android 帧动画打造动态ImageView

实现

新建AnimatorImageView 继承AppCompatImageView/ImageView

public class AnimatorImageView extends AppCompatImageView {

    public AnimatorImageView(Context context) {
        super(context);
    }

    public AnimatorImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public AnimatorImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (getVisibility() == VISIBLE) {
            animator(true);
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        animator(false);
    }

    @Override
    public void setVisibility(int visibility) {
        super.setVisibility(visibility);
        if (VISIBLE == visibility) {
            animator(true);
        } else {
            animator(false);
        }
    }

    /**
     * 启动或停止动画
     * @param start
     *          true为启动动画; false为停止动画
     */
    public void animator(boolean start) {
        try {
            AnimationDrawable animationDrawable = (AnimationDrawable) getDrawable();
            if (animationDrawable == null) {
                return;
            }
            animationDrawable.stop();
            if (start) {
                animationDrawable.start();
            }
        } catch (Exception e) {
            Log.e("AnimatorImageView", e.getMessage());
        }
    }
}

调用

1、drawable中新建animation-list文件practicing_animator.xml



    
    
    
    

2、layout布局文件中调用(调用方式与ImageView相同)


你可能感兴趣的:(Android 帧动画打造动态ImageView)