Android动画之帧动画

本文介绍如何使用帧动画创建视图背景动画效果。通过XML文件定义一系列图片帧,并设置每帧显示时长,最终实现循环播放的动画效果。文章还讨论了在不同Activity生命周期阶段启动动画的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过定义一系列的drawable对象来创建一个帧动画,被用于一个视图的背景。

创建帧动画最简单的方式是定义一个XML的动画文件,放res/drawable/目录下并将其设置为一个视图对象的背景,然后调用start()方法运行动画。

一个帧动画的XML文件有一个和一系列内嵌的标签组成。每一项定义一帧动画,如下:

spin_animation.xml file in res/drawable/ folder:

<animation-list android id="@+id/selected" android oneshot="false">
     <item android:drawable="@drawable/wheel0" duration="100"/>
     <item android:drawable="@drawable/wheel1" duration="100"/>
     <item android:drawable="@drawable/wheel2" duration="100"/>
     <item android:deawable="@drawable/wheel3" duration="100"/>
</animation-list>

注:

oneshot:为true时动画将只运行一次后就停止;为false动画将不停循环;

drawable:设置每帧动画显示的内容;

duration:设置每帧的显示时长,毫秒。

variablePadding:如果为true,允许drawable的padding根据当前的选择状态改变。

visible:提供drawable的初始可见状态,默认为false。

加载动画的代码:

ImageViewimg=(ImageView)findViewById(R.id.spinning_wheel_image);

img.setBackgroundResource(R.drawable.spin_animation);

AnimationDrawableframeAnimation=(AnimationDrawable)img.getBackground();

frameAnimation.start();

更多:

It’s important to note that the start() method called on the AnimationDrawable cannot be called during the onCreate() method of your Activity, because the AnimationDrawable is not yet fully attached to the window.(来自官方文档)

在Activity的onCreate()方法中不能调用帧动画的start()方法,因为帧动画尚未完全的加载到窗口上。你可以在Activity的onWindowFouseChanged()方法中调用动画。

但是:

如果在布局中给ImageView设置背景:

android:background="@drawable/spin_animation"

然后在Activity的onCreate()方法中调用:

ImageViewimg=(ImageView)findViewById(R.id.spinning_wheel_image);

AnimationDrawableframeAnimation=(AnimationDrawable)img.getBackground();

frameAnimation.start();

上述情况是可行的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值