AnimationDrawable的使用

1.定义

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


2.使用

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

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

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


3.实例

/res/drawable/下的xml文件:




    
    
    
    
    


代码:

public class MainActivity extends Activity implements OnClickListener{

	private Button startBtn = null;
	private Button stoptBtn = null;
	private ImageView animIv = null;
	private AnimationDrawable ad = null;

	@Override
	protected 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);
		
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(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,报空指针异常。



你可能感兴趣的:(AnimationDrawable的使用)