I write the custom ImageView
to display an animation with list of bitmaps. Here is my source code:
public class CustomImageView extends ImageView {
public CustomImageView(Context context) {
super(context);
}
public void startAnimation(List<BitmapDrawable> arrBitmapDelay, int[] durations) {
if (arrBitmapDelay.size() > 1 && arrBitmapDelay.size() == durations.length) {
final AnimationDrawable oAnimation = new AnimationDrawable();
oAnimation.setOneShot(false);
int i = 0;
for (BitmapDrawable oBitmapDelay : arrBitmapDelay) {
oAnimation.addFrame(oBitmapDelay, durations[i]);
i++;
}
if(getContext() instanceof Activity)
if(((Activity)getContext()).isFinishing())
return;
if(oAnimation.getNumberOfFrames()<=0) return;
setImageDrawable(oAnimation);
post(new Runnable() {
@Override
public void run() {
oAnimation.start();
}
});
}
}
}
And the result: https://goo.gl/photos/FSC5RaEE2ajfe23v6
You can see, it loop correctly time, but sometimes it flashing... Please help!
I add code of reading list bitmap.
public void decodeAndShow() {
List<Bitmap> bitmaps = new ArrayList<>();
int[] duration = new int[20];
for (int i=0; i<20; i++) {
bitmaps.add(BitmapFactory.decodeFile(new File(getContext().getCacheDir(), "bitmapsample"+i+".png").getAbsolutePath()));
duration[i] = 100;
}
img.startAnimation(bitmaps, duration);
}
Sorry, because my project is too much complicated to copy here.
I fixed by myself with a cheat. I don't know why it's OK.
This is my code:
public class CustomImageView extends ImageView {
private Runnable runningAnimation;
public CustomImageView(Context context) {
super(context);
}
public void startAnimation(List<BitmapDrawable> arrBitmapDelay, int[] durations) {
if(runningAnimation != null) {
this.removeCallbacks(runningAnimation);
}
if (arrBitmapDelay.size() > 1 && arrBitmapDelay.size() == durations.length) {
final AnimationDrawable oAnimation = new AnimationDrawable();
oAnimation.setOneShot(false);
int i = 0;
for (BitmapDrawable oBitmapDelay : arrBitmapDelay) {
oAnimation.addFrame(oBitmapDelay, durations[i]);
i++;
}
if(getContext() instanceof Activity)
if(((Activity)getContext()).isFinishing())
return;
if(oAnimation.getNumberOfFrames()<=0) return;
setImageDrawable(oAnimation);
runningAnimation = new Runnable() {
@Override
public void run() {
oAnimation.start();
}
}
post(runningAnimation);
}
}
}