关于逐帧动画网上的教程很多,大多数是介绍通过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://code.google.com/p/android/issues/detail?id=14863