Created
January 21, 2013 13:52
-
-
Save Qw4z1/4586204 to your computer and use it in GitHub Desktop.
Optimized ImageView
This file contains hidden or 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; | |
/** | |
* | |
* ImageView using the optimization from Jelly Bean. | |
* | |
* @author Viktor Nyblom | |
* | |
*/ | |
public class OptimizedImageView extends ImageView { | |
private boolean mIgnoreNextRequestLayout = false; | |
public OptimizedImageView(Context context) { | |
super(context); | |
} | |
public OptimizedImageView(Context context, AttributeSet attrs) { | |
super(context, attrs); | |
} | |
public OptimizedImageView(Context context, AttributeSet attrs, int defStyle) { | |
super(context, attrs, defStyle); | |
} | |
@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