0

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?

Jake Lee
  • 7,549
  • 8
  • 45
  • 86
vinom
  • 17
  • 3
  • 1
    you need 2 objects AnimationDrawable animation1, animation2. Then animation2.addFrame(new BitmapDrawable(bitmapba2), 20); myimage2.setImageDrawable(animation2); – Style-7 Jan 28 '19 at 19:09
  • I do this but I want another more effective if i want to do declared 100 imageview It is not logical animation1, animation2...animation100 same bitmap1,bitmap2 this repetition (Load on memory). – vinom Jan 28 '19 at 20:17

1 Answers1

0

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.

frumle
  • 593
  • 5
  • 15