I have only one ImageView in my layout and I am changing its resource when a gasture event detected. I just want to show an animation while changing resource of
I found another way to animate it using transition drawable(I took idea from here)
public static void setImageDrawableWithAnimation(ImageView imageView,
Drawable drawable,
int duration) {
Drawable currentDrawable = imageView.getDrawable();
if (currentDrawable == null) {
imageView.setImageDrawable(drawable);
return;
}
TransitionDrawable transitionDrawable = new TransitionDrawable(new Drawable[] {
currentDrawable,
drawable
});
imageView.setImageDrawable(transitionDrawable);
transitionDrawable.startTransition(duration);
}
Analogous kotlin extension function:
fun ImageView.setImageDrawableWithAnimation(drawable: Drawable, duration: Int = 300) {
val currentDrawable = getDrawable()
if (currentDrawable == null) {
setImageDrawable(drawable)
return
}
val transitionDrawable = TransitionDrawable(arrayOf(
currentDrawable,
drawable
))
setImageDrawable(transitionDrawable)
transitionDrawable.startTransition(duration)
}
If your drawables contains transparent parts, this flag could be useful to prevent old drawable visibility:
transitionDrawable.setCrossFadeEnabled(true);