Android 帧动画打造动态ImageView
2018-12-28 本文已影响7人
房嘻
实现
新建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" />