Android 幀動畫打造動態ImageView

weixin_34402408發表於2018-12-28

實現

新建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

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:duration="200" android:drawable="@mipmap/practicing1" />
    <item android:duration="200" android:drawable="@mipmap/practicing2" />
    <item android:duration="200" android:drawable="@mipmap/practicing3" />
    <item android:duration="200" android:drawable="@mipmap/practicing4" />
</animation-list>

2、layout佈局檔案中呼叫(呼叫方式與ImageView相同)

<xxx.xxx.xxx.AnimatorImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/practicing_animator" />

相關文章