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

来源:互联网 发布:电脑淘宝商品链接 编辑:程序博客网 时间:2024/05/18 13:41

首先创建一个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()里,因为这时候应用窗体还没加载完毕了。。启动动画两种方式,手动的,比如在一个按钮的点击事件里,启动。

 

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

 

@Overridepublic 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 theonCreate(Bundle) method of your activity, because theAnimationDrawable 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.

 

原创粉丝点击