程序员首页投稿(暂停使用,暂停投稿)Android技术知识

Android Drawable Animation

2016-04-14  本文已影响2257人  smart_dev
帧动画

上面这个效果是某软件上的一个loading效果,怎么实现呢?

概述:


像电影一样,以一个顺序来逐帧播放图片资源,这种动画故称作帧动画。Android同样提供了两种实现方式,代码中和xml中实现:

使用

动画文件存放位置:

res/drawable/filename.xml

资源引用:

In Java: R.drawable.filename
In XML: @[package:]drawable.filename

XML中语义

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot=["true" | "false"] >
    <item
        android:drawable="@[package:]drawable/drawable_resource_name"
        android:duration="integer" />
</animation-list>

OK,直接贴出上面的loading效果实现代码

动画文件

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:drawable="@drawable/a76"
        android:duration="70" />
    <item
        android:drawable="@drawable/a77"
        android:duration="70" />
    <item
        android:drawable="@drawable/a78"
        android:duration="70" />
   
</animation-list>

对应的三张资源文件

a76.png
a77.png
a78.png

布局文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.smart.myapplication.animation.FrameActivity">

    <ImageView
        android:id="@+id/imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="@drawable/loading1"
        android:scaleType="center" />

    <Button
        android:id="@+id/start_anim"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="开启动画" />

</RelativeLayout>

activity中:

private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_frame);
    imageView = (ImageView) findViewById(R.id.imageview);
    findViewById(R.id.start_anim).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // 获取AnimationDrawable对象
            AnimationDrawable animationDrawable = (AnimationDrawable) imageView.getBackground();

            if (animationDrawable.isRunning()) { //判断这个动画是否正在运行
                animationDrawable.stop(); // 停止
            } else {
                animationDrawable.start(); // 启动
            }
        }
    });
}

至此上面那个效果实现了。

如果在Activity中我不想用按钮触发这个动画,要程序运行即播放动画,怎么做呢?
最好是在onWindowFocusChanged这个方法中启动动画。因为在onCreate中启动动画, AnimationDrawable有可能还没有完全attach 到Window上

另外AnimationDrawable其他几个重要的方法

关于Android其他Drawable资源的使用

上一篇 下一篇

猜你喜欢

热点阅读