1 package com.bumptech.glide.request.animation; 2 3 import android.graphics.drawable.Drawable; 4 import android.graphics.drawable.TransitionDrawable; 5 6 /** 7 * A cross fade {@link GlideAnimation} for {@link android.graphics.drawable.Drawable}s 8 * that uses an {@link android.graphics.drawable.TransitionDrawable} to transition from an existing drawable 9 * already visible on the target to a new drawable. If no existing drawable exists, this class can instead fall back 10 * to a default animation that doesn't rely on {@link android.graphics.drawable.TransitionDrawable}. 11 * 12 * @param <T> The type of the {@link android.graphics.drawable.Drawable} that will be animated. 13 */ 14 public class DrawableCrossFadeViewAnimation<T extends Drawable> implements GlideAnimation<T> { 15 private final GlideAnimation<T> defaultAnimation; 16 private final int duration; 17 18 /** 19 * Constructor that takes a default animation and a duration in milliseconds that the cross fade animation should 20 * last. 21 * @param duration The duration that the cross fade animation should run if there is something to cross fade from 22 * when a new {@link android.graphics.drawable.Drawable} is set. 23 */ DrawableCrossFadeViewAnimation(GlideAnimation<T> defaultAnimation, int duration)24 public DrawableCrossFadeViewAnimation(GlideAnimation<T> defaultAnimation, int duration) { 25 this.defaultAnimation = defaultAnimation; 26 this.duration = duration; 27 } 28 29 /** 30 * Animates from the previous drawable to the current drawable in one of two ways. 31 * 32 * <ol> 33 * <li>Using the default animation provided in the constructor if the previous drawable is null</li> 34 * <li>Using the cross fade animation with the duration provided in the constructor if the previous 35 * drawable is non null</li> 36 * </ol> 37 * 38 * @param current {@inheritDoc} 39 * @param adapter {@inheritDoc} 40 * @return {@inheritDoc} 41 */ 42 @Override animate(T current, ViewAdapter adapter)43 public boolean animate(T current, ViewAdapter adapter) { 44 Drawable previous = adapter.getCurrentDrawable(); 45 if (previous != null) { 46 TransitionDrawable transitionDrawable = new TransitionDrawable(new Drawable[] { previous, current }); 47 transitionDrawable.setCrossFadeEnabled(true); 48 transitionDrawable.startTransition(duration); 49 adapter.setDrawable(transitionDrawable); 50 return true; 51 } else { 52 defaultAnimation.animate(current, adapter); 53 return false; 54 } 55 } 56 } 57