Android动画框架学习之FrameAnimation练习

这个框架很明显,需要我们提供一帧一帧的图片,然后达到循环播放的效果,跟我们小时候看的电视的实现原理一样。

下面是具体过程:

1.)在res/drawable目录下一个文件lottery_animlist.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="@mipmap/lottery_1"
        android:duration="200" />
    <item
        android:drawable="@mipmap/lottery_2"
        android:duration="200" />
    <item
        android:drawable="@mipmap/lottery_3"
        android:duration="200" />
    <item
        android:drawable="@mipmap/lottery_4"
        android:duration="200" />
    <item
        android:drawable="@mipmap/lottery_5"
        android:duration="200" />
    <item
        android:drawable="@mipmap/lottery_6"
        android:duration="200" />

</animation-list>

复制代码

根节点是animation-list(动画列表),里面有一个或者多个item节点组成,oneshot属性表示是否只播放一次,true表示只会播放一次,false表示一直循环播放,内部用item节点声明一个动画帧,android:drawable指定此帧动画所对应的图片资源,android:druation代表此帧持续的时间,整数,单位为毫秒。

注意:

   之前使用eclipse或者Android ADT开发的时候,文件可以放在res/anim和res/drawable两个文件夹下面,虽然谷歌推荐放在res/drawable文件夹下但是不会报错,在使用Android studio时候就没那么幸运了,如果不放在res/drawable文件夹下面会报如下错误:

2.)用ImageView控件作为动画载体来显示动画

复制代码

 <ImageView
   android:id="@+id/animation_iv"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_gravity="center"
   android:layout_margin="10dp"
   android:src="@drawable/lottery_animlist" />

复制代码

这个时候我们运行一下,发现动画没有运行而是停留在第一帧,那是因为AnimationDrawable播放动画是依附在window上面的,而在Activity onCreate方法中调用时Window还未初始化完毕,所有才会停留在第一帧,要想实现播放必须在onWindowFocusChanged中添加如下代码:

imageView.setImageResource(R.drawable.lottery_animlist);
AnimationDrawable animationDrawable = (AnimationDrawable) imageView.getDrawable();
animationDrawable.start();

如果想要停止播放动画可以调用AnimationDrawable的stop方法

  imageView.setImageResource(R.drawable.lottery_animlist);
  AnimationDrawable animationDrawable = (AnimationDrawable) imageView.getDrawable();
  animationDrawable.stop();

3.)纯Java代码实现方式

复制代码

AnimationDrawable anim = new AnimationDrawable();
    for (int i = 1; i <= 6; i++) {
    int id = getResources().getIdentifier("lottery_" + i, "mipmap", getPackageName());
    Drawable drawable = getResources().getDrawable(id);
    anim.addFrame(drawable, 200);
    }
    anim.setOneShot(false);
    imageView.setImageDrawable(anim);
    anim.start();

复制代码

4.)AnimationDrawable 几个常见的api

  • void start() - 开始播放动画

  • void stop() - 停止播放动画

  • addFrame(Drawable frame, int duration) - 添加一帧,并设置该帧显示的持续时间

  • void setOneShoe(boolean flag) - false为循环播放,true为仅播放一次

  • boolean isRunning() - 是否正在播放

实现效果:

由于我没找到连续变化的图片,所以我是用两张不同的图片来回切换。要想实现按钮控制动画的开始与停止,添加一个flag就行。

转载:http://www.cnblogs.com/whoislcj/p/5733740.html

猜你喜欢

转载自blog.csdn.net/cyanchen666/article/details/82115915