AnimationDrawable android 工作室中的问题

Problem in AnimationDrawable android studio

我有我想要的 animationdrawable,但在两个 imageview 中有相同的 animationdrawable。 问题第一个不行,第二个不行。

AnimationDrawable animation1 = new AnimationDrawable();
Bitmap bitmapba1 = BitmapFactory.decodeResource(getResources(),R.drawable.a);
Bitmap bitmapba2 = BitmapFactory.decodeResource(getResources(), R.drawable.b);
bitmapba1=Bitmap.createScaledBitmap(bitmapba1,x,x,false);
bitmapba2=Bitmap.createScaledBitmap(bitmapba2,x,x,false);
animation1.addFrame(new BitmapDrawable(bitmapba1), 20);
animation1.addFrame(new BitmapDrawable(bitmapba2), 20);
myimage1.setImageDrawable(animation1);
myimage2.setImageDrawable(animation1);

问题已解决但效率低下(原始)我声明第二个 animation2 相同的 bitmapba1 和 bitmapba2 :animation2.addFrame(...(bitmapba1), 20) 和 animation2.addFrame(...(bitmapba2 ), 20).

问题是如果有 100 个 imageview 共享同一个 animationdrawable 怎么办?

正如 Style-7 所写,对于 ImageView 的每个实例,您应该创建自己的 AnimationDrawable 实例。问题是 AnimationDrawable 的一个实例有它自己的状态。一旦您在多个视图之间共享此单个实例,此状态 'tears'。

但是你不应该为每个动画保留位图的副本。 加载一次,然后只需配置动画。

Bitmap bitmapba1 = BitmapFactory.decodeResource(getResources(),R.drawable.a);
Bitmap bitmapba2 = BitmapFactory.decodeResource(getResources(), R.drawable.b);
bitmapba1=Bitmap.createScaledBitmap(bitmapba1,x,x,false);
bitmapba2=Bitmap.createScaledBitmap(bitmapba2,x,x,false);

for(ImageView view : listOfViews){
    AnimationDrawable animation = new AnimationDrawable();
    animation.addFrame(new BitmapDrawable(bitmapba1), 20);
    animation.addFrame(new BitmapDrawable(bitmapba2), 20);
    view.setImageDrawable(animation);
}

我们还应该为每个动画实例创建 BitmapDrawable 的新实例,因为它也有自己的状态。但是每个这样的新实例只保留对 Bitmap 对象的引用,不会为每个新实例复制位图数据。