Drawable animation是什么?
Drawable animation是一种动画类型。
Drawable animation的用途?
Drawable animation可以用来以你指定的顺序播放一组图片。可以循环播放,也可以只播放一次。
Drawable animation怎么使用?
Drawable animation可以在任何View上面使用,首先用AnimationDrawable对象设置View的Background,然后调用AnimationDrawable对象的start()
方法开始动画。
具体步骤如下:
1.用AnimationDrawable对象设置View的Background,有三种方式:
- [1].通过调用View的
setBackgroundResource(R.drawable.mydrawable)
方法设置View的Background [2].通过设置View的XML属性
and(和谐)roid:background="@drawable/mydrawable"
<?xml version="1.0" encoding="utf-8"?> <!-- 方式[1]、[2]用到的 mydrawable.xml --> <animation-list xmlns:android="http://schemas.android.com/apk/res/android" > <item android:drawable="@drawable/first" android:duration="300"/> <item android:drawable="@drawable/second" android:duration="300"/> <item android:drawable="@drawable/third" android:duration="300"/> </animation-list>
- [3].通过代码创建AnimationDrawable对象,用其设置View的Background
//方式[3]用到的代码
AnimationDrawable animationDrawable = new AnimationDrawable();
animationDrawable.addFrame(getResources().getDrawable(R.drawable.first),300);
animationDrawable.addFrame(getResources().getDrawable(R.drawable.second),300);
animationDrawable.addFrame(getResources().getDrawable(R.drawable.third),300);
animationDrawable.setOneShot(false);//设置循环一次就停止为false,即循环播放
imageView.setBackgroundDrawable(animationDrawable);
2.用AnimationDrawable对象的start()
方法
((AnimationDrawable)imageView.getBackground()).start();
注意事项
SDK文档里面有这么一段话
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. If you want to play the animation immediately, without requiring interaction, then you might want to call it from the onWindowFocusChanged() method in your Activity, which will get called when Android brings your window into focus.
因此我们不能在Activity的onCreate()
方法里面调用View的start()
,而是在Activity的onWindowFocusChanged()
方法里面调用View的start()