Last active
January 8, 2020 02:14
-
-
Save chrisbanes/4555987 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context; | |
import android.graphics.drawable.Drawable; | |
import android.os.Build.VERSION; | |
import android.os.Build.VERSION_CODES; | |
import android.util.AttributeSet; | |
import android.widget.ImageView; | |
public class OptimisedImageView extends ImageView { | |
private boolean mIgnoreNextRequestLayout = false; | |
public OptimisedImageView(Context context, AttributeSet attrs) { | |
super(context, attrs); | |
} | |
@Override | |
public void setImageDrawable(final Drawable newDrawable) { | |
if (VERSION.SDK_INT < VERSION_CODES.JELLY_BEAN_MR1) { | |
// The currently set Drawable | |
final Drawable oldDrawable = getDrawable(); | |
if (null != oldDrawable && oldDrawable != newDrawable) { | |
final int oldWidth = oldDrawable.getIntrinsicWidth(); | |
final int oldHeight = oldDrawable.getIntrinsicHeight(); | |
/** | |
* Ignore the next requestLayout call if the new Drawable is the | |
* same size as the currently displayed one. | |
* */ | |
mIgnoreNextRequestLayout = oldHeight == newDrawable.getIntrinsicHeight() | |
&& oldWidth == newDrawable.getIntrinsicWidth(); | |
} | |
} | |
// Finally, call up to super | |
super.setImageDrawable(newDrawable); | |
} | |
@Override | |
public void requestLayout() { | |
if (!mIgnoreNextRequestLayout) { | |
super.requestLayout(); | |
} | |
// Reset Flag so that the requestLayout() will work again | |
mIgnoreNextRequestLayout = false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment