关于代码实现 AnimationDrawable 的问题

关于逐帧动画网上的教程很多,大多数是介绍通过xml 文件来实现。但有时候我们要播放多个动画,若要通过xml的话就需要创建多个xml文件,这样的话可扩展性较低。所以我们就很容易会想到在代码中动态去加载图片,动态生成AnimationDrawable。于是我们这样写

	private void startAnimation() {
		loadView2 = (ImageView) findViewById(R.id.load2);
		AnimationDrawable anim = new AnimationDrawable();
		for (int i = 1; i < 4; i++) {
			int id = getResources().getIdentifier("load" + i, "drawable",
					LoadActivity.this.getPackageName());
			Drawable mBitAnimation = getResources().getDrawable(id);
			anim.addFrame(mBitAnimation, 500);
		}
		anim.setOneShot(false);
		loadView2.setBackgroundDrawable(anim);
		anim.start();
	}

对应的imageView:

    <ImageView
        android:id="@+id/load1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/load"/>


但这样写就要注意了, 调用startAnimation()方法不能在onCreate()方法中。(可以在onResume中)


还有另一种写法,  startAnimation方法:


		anim = new AnimationDrawable();
		for (int i = 1; i < 4; i++) {

			int id = getResources().getIdentifier("load" + i, "drawable",
					LoadActivity.this.getPackageName());
			Drawable mBitAnimation = getResources().getDrawable(id);
			anim.addFrame(mBitAnimation, 500);
		}
		anim.setOneShot(false);
		// 开始播放动画
		loadView2.setBackgroundDrawable(anim);
		loadView2.post(anim);

但这样写要注意了,在xml文件中   imageView 一定要设置确定的高 和宽 或者设成  fill_parent, 不能是wrap_content。 这样写的话就可以在onCreate()方法中调用了。但是这样的话会有一个问题,程序第一次可以正常播放动画,但退出后再进来就不播了,太纠结了!! 还没找到原因……


参考自两个帖子:

http://androidforums.com/application-development/11620-programmatic-frame-frame-animation-examle-animationdrawable.html

http://code.google.com/p/android/issues/detail?id=14863




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值