Android 逐帧动画

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/BlueSky003/article/details/86639121

1、本质:按序播放一组预先定义好的图片。
2、作用对象:视图控件(View):TextView、ImageView 等。
3、优点:简单、方便;缺点:容易引起 OOM,如果使用大量,尺寸较大的图片资源
4、具体使用

  1. 在 res/drawable 下新建逐帧动画的资源文件 anim_loading.xml
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="false">// 设置是否只播放一次,默认为false
    // item = 动画图片资源;duration = 设置一帧持续时间(ms)
    <item
        android:drawable="@drawable/loadload0001"
        android:duration="50"/>
    <item
        android:drawable="@drawable/loadload0002"
        android:duration="50"/>
    <item
        android:drawable="@drawable/loadload0003"
        android:duration="50"/>
    <item
        android:drawable="@drawable/loadload0004"
        android:duration="50"/>
</animation-list>
  1. 在布局文件引用或者代码动态设置动画,src、background
    <ImageView
        android:id="@+id/iv_anim"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/anim_loading"/>
    <TextView
        android:id="@+id/tv_anim"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/anim_loading"/>
  1. 播放动画
    private ImageView iv_anim;
    private TextView tv_anim;
    private AnimationDrawable mIvAnim,mTvAnim;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        iv_anim = findViewById(R.id.iv_anim);
        tv_anim = findViewById(R.id.tv_anim);
     
        mIvAnim = (AnimationDrawable)iv_anim.getDrawable();  // 获取动画对象
        mTvAnim = (AnimationDrawable)tv_anim.getBackground();
        mIvAnim.start(); // 启动动画
        mTvAnim.start();
        // mTvAnim.stop(); // 暂停动画
    }

猜你喜欢

转载自blog.csdn.net/BlueSky003/article/details/86639121