如果需要,可以在运行时创建或者修改动画 drawables:AnimationDrawable createFrom(Context context, int id1, int id2) {
AnimationDrawable ad = new AnimationDrawable();
ad.addFrame(context.getResources().getDrawable(id1), 1000);
ad.addFrame(context.getResources().getDrawable(id2), 1000);
return ad;
}
使用 上面,你可以执行以下操作:ImageView img = (ImageView)findViewById(R.id.imageView1);
img.setBackground(createFrom(this, R.drawable.barbellcurl1, R.drawable.barbellcurl2));
你还应该有同样的结果。
使用类型化 array 应该像这样工作:AnimationDrawable createFromArray(Context context, int arrayId) {
TypedArray array = context.getResources().obtainTypedArray(arrayId);
AnimationDrawable ad = new AnimationDrawable();
for (int i = 0; i
ad.addFrame(array.getDrawable(i), 1000);
}
array.recycle();
return ad;
}
XML文件的内容看起来像 res/values/gifs.xml<?xml version="1.0" encoding="utf-8"?>
@drawable/barbellcurl1
@drawable/barbellcurl2
@drawable/cat
@drawable/dog
为了在代码中找到一个可以绘制的东西 createFromArray(this, R.array.gif1) 等等.
在最后 onCreate 中的代码将是@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progress);
ImageView img = (ImageView)findViewById(R.id.imageView1);
AnimationDrawable ad = createFrom(this, R.drawable.barbellcurl1, R.drawable.barbellcurl2);
//OR
AnimationDrawable ad = createFromArray(this, R.array.gif1);
ad.setOneShot(false);
img.setBackground(ad);
ad.start();
}