AnimationDrawable的使用

来源:互联网 发布:android ui优化 编辑:程序博客网 时间:2024/06/05 06:17

1.定义

AnimationDrawable:一个用来创建帧动画的对象,由一系列的Drawable对象定义,可以设置成一个View对象的背景。


2.使用

(1)在/res/drawable目录下,新建一个xml文件,定义<animation-list>根节点,在其中可以使用android:oneshot="true"或者android:oneshot="false"来标示是否需要循环播放。

在根节点中使用<item>来定义动画需要显示的帧,其中使用android:drawable=@drawable/xxx"来使用Drawable资源,使用android:duration="xx"来控制一张图片显示的时间。

(2)在代码中,把ImageView的背景先设置成在drawable中定义的xml文件,然后定义AnimationDrawable对象,AnimationDrawable对象初始化为由ImageView获得的背景资源。然后使用AnimationDrawable的start()和stop()函数来控制播放。


3.实例

/res/drawable/下的xml文件:

<?xml version="1.0" encoding="utf-8"?><animation-list xmlns:android="http://schemas.android.com/apk/res/android"    android:oneshot="false" >    <item        android:drawable="@drawable/first"        android:duration="60"/>    <item        android:drawable="@drawable/second"        android:duration="60"/>    <item        android:drawable="@drawable/third"        android:duration="60"/>    <item        android:drawable="@drawable/forth"        android:duration="60"/>    <item        android:drawable="@drawable/fifth"        android:duration="60"/></animation-list>


代码:

public class MainActivity extends Activity implements OnClickListener{private Button startBtn = null;private Button stoptBtn = null;private ImageView animIv = null;private AnimationDrawable ad = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);startBtn = (Button) findViewById(R.id.start_btn);stoptBtn = (Button) findViewById(R.id.stop_btn);animIv = (ImageView) findViewById(R.id.anim_iv);//若不设置背景资源,则得到的ad为null,frame_anim为自定义的要显示的图片animIv.setBackgroundResource(R.drawable.frame_anim);//在layout文件中,animIv不能设置背景,//否则此时animIv.getBackground()得到的是BitmapDrawable,转换成AnimationDrawable会报错ad = (AnimationDrawable) animIv.getBackground();startBtn.setOnClickListener(this);stoptBtn.setOnClickListener(this);}@Overridepublic void onClick(View v) {// TODO Auto-generated method stubswitch(v.getId()){case R.id.start_btn:ad.start();break;case R.id.stop_btn:ad.stop();break;}}}

4.遇到的一些问题

(1)在xml文件中给ImageView设置背景为一张图片,然后代码中没有写setBackgroundResource,导致出现

android.graphics.drawable.BitmapDrawable cannot be cast to android.graphics.drawable.AnimationDrawable 错误而不能正常运行

(2)没有给ImageView设置背景资源,导致ad = (AnimationDrawable) animIv.getBackground()为null,报空指针异常。



0 0
原创粉丝点击