android中通过AnimationDrawable实现动画背景图片

本文介绍了如何在Android中使用AnimationDrawable创建动画背景图片。首先在XML中配置多帧图片,设定间隔时间和循环播放属性。然后将XML资源设为背景,通过强转为AnimationDrawable并调用start()方法启动动画。注意start()方法不能在onCreate()中调用,可选择在按钮点击事件或onWindowFocusChanged()中启动。提供了API描述以帮助理解。

首先创建一个XML文件,里边有很多张图片,记得type类型选择 drawable。 root element选择如下的animation-list

<!-- Animation frames are wheel0.png -- wheel5.png files inside the 
 res/drawable/ folder --> 
 <animation-list android:id="@+id/selected" android:oneshot="false"> 
    <item android:drawable="@drawable/wheel0" android:duration="50" /> 
    <item android:drawable="@drawable/wheel1" android:duration="50" /> 
    <item android:drawable="@drawable/wheel2" android:duration="50" /> 
    <item android:drawable="@drawable/wheel3" android:duration="50" /> 
    <item android:drawable="@drawable/wheel4" android:duration="50" /> 
    <item android:drawable="@drawable/wheel5" android:duration="50" /> 
 </animation-list>


上边的图片就是很多帧图片组合成一个动态的图片。。后边的参数是间隔时间50毫秒,  oneshot属性为false,表示循环播放,不是只循环一次。。

后边就是如下代码了,把这个资源文件设置为一个背景,再获取这个背景,强转为AnimationDrawable,之后调用start()方法开启,停止动画是stop();

 

// Load the ImageView that will host the animation and 
 // set its background to our AnimationDrawable XML resource. 
 ImageView img = (ImageView)findViewById(R.id.spinning_wheel_image); 
 img.setBackgroundResource(R.drawable.spin_animation); 
 
 // Get the background, which has been compiled to an AnimationDrawable object. 
 AnimationDrawable frameAnimation = (AnimationDrawable) img.getBackground(); 
 
 // Start the animation (looped playback by default). 
 frameAnimation.start(); 


需要说明的一点是,start方法不能使用在oncreate()里,因为这时候应用窗体还没加载完毕了。。启动动画两种方式,手动的,比如在一个按钮的点击事件里,启动。

 

另一个,自动启动,重写下边的方法。就是应用程序窗体是否加载完毕并获得了焦点。

 

@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		if(hasFocus)anim.start();
		else anim.stop();
		super.onWindowFocusChanged(hasFocus);
	}


刚开始弄这个,为了实现自动开启动画,我还弄了个handler来开启动画,后来看了API才找到上边简单的方法,希望对大家有帮助。

下边是API的描述:

public void start ()
Added in API level 1

Starts the animation, looping if necessary. This method has no effect if the animation is running. Do not call this in the onCreate(Bundle) method of your activity, because the AnimationDrawable is not yet fully attached to the window. If you want to play the animation immediately, without requiring interaction, then you might want to call it from the onWindowFocusChanged(boolean) method in your activity, which will get called when Android brings your window into focus.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值