Android动画-Frame Animation(帧动画)

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

Android动画主要分为以下三类:

  1. Tweened animation(补间动画)- 在android3.0(API11)之前支持,该动画仅仅支持对View操作,而且View在做动画的时候,View相应的实际属性值并没有发生改变,例如:一个Button起始位置left,top,right,bottom为(0, 0, 50, 50),经过水平平移50操作移到(50, 0, 100, 50),然后将该Button固定在平移后的位置,这时候Button的点击事件的触发区域仍然是(0, 0, 50, 50)。
  2. Frame animation(帧动画)- 在android3.0(API11)之前支持,该动画顺序播放事先准备好的图像,类似于放电影。
  3. Property animation(属性动画)- 在android3.0(API11)开始支持,属性动画不像补间动画,属性动画通过改变对象的实际属性来实现动画,而且属性动画操作的对象不局限于View。

在本文中,主要介绍Frame animation(帧动画)的相关使用。

首先,在drawable文件下准备若干图片,比如detail1.png、detail2.png、detail3.png、detail4.png和detail5
.png。

1. 帧动画在xml中的使用

在drawable文件夹下新建一个animation_list.xml文件,文件内容如下:

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="false">
    <item android:drawable="@drawable/detail1" android:duration="500"/>
    <item android:drawable="@drawable/detail2" android:duration="500"/>
    <item android:drawable="@drawable/detail3" android:duration="500"/>
    <item android:drawable="@drawable/detail4" android:duration="500"/>
    <item android:drawable="@drawable/detail5" android:duration="500"/>
</animation-list>

android:oneshot = “false”表示动画重复运行,”true”表示动画只允许一次;
android:duration = “500”表示一帧持续的时间。

animation_list.xml在代码中的应用:

mButton = (Button) findViewById(R.id.button);
mImageView = (ImageView) findViewById(R.id.imageView);
mImageView.setBackgroundResource(R.drawable.animation_list);
mButton.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
            AnimationDrawable animationDrawable = (AnimationDrawable) mImageView.getBackground();
            animationDrawable.start();
       }
 });

2. 帧动画在代码中的使用

private void createAnimationList(){
        AnimationDrawable animationDrawable = new AnimationDrawable();
        animationDrawable.setOneShot(false);
        for (int i=0; i<5;){
            // 根据包名、文件名以及文件类型找到文件对应的id
            int id = getResources().getIdentifier("detail" + ++i, "drawable", getPackageName());
            // 根据id找到对应的资源
            Drawable drawable = getResources().getDrawable(id);
            // 将图片添加进入AnimationDrawable作为一帧
            animationDrawable.addFrame(drawable, 1000);
        }
        mImageView.setBackgroundDrawable(animationDrawable);
}
mButton = (Button) findViewById(R.id.button);
mImageView = (ImageView) findViewById(R.id.imageView);
createAnimationList();
mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             AnimationDrawable animationDrawable = (AnimationDrawable) mImageView.getBackground();
             animationDrawable.start();
        }
});

注意: 帧动画的start函数不能在onCreate中直接调用,因为这个时候窗口还没有完全建立好,动画不会按照预期运行。

猜你喜欢

转载自blog.csdn.net/xiayong1/article/details/53645022