I have animationdrawable I want to but same animationdrawable in two imageview. The problem the first do not work and the second work.
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);
The problem solved but inefficient (primitive) I declared second animation2 same bitmapba1 and bitmapba2 : animation2.addFrame(...(bitmapba1), 20), and animation2.addFrame(...(bitmapba2), 20).
The question is what to do if there are 100 imageview they share same one animationdrawable?
As Style-7 wrote, for each instance of ImageView
you should create its own instance of AnimationDrawable
. The problem is that an instance of AnimationDrawable
has its own state. This state 'tears' as soon as you share this single instance between multiple views.
But you should not keep the copy of bitmaps for each animation. Load them once and then just configure animations.
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);
}
We also should create the new instance of BitmapDrawable
for each animation instance since it also has its own state . But each of such new instance just keeps the reference to the Bitmap
object and does not copy the bitmap data for every new one.