Created
March 18, 2019 06:52
-
-
Save iamdeveloper-lopez/38f80f02b6e814d1097bf44f60f24a42 to your computer and use it in GitHub Desktop.
An ImageView layout that maintains a consistent width to height aspect ratio.
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
public class DynamicHeightImageView extends ImageView { | |
private double mHeightRatio; | |
public DynamicHeightImageView(Context context, AttributeSet attrs) { | |
super(context, attrs); | |
} | |
public DynamicHeightImageView(Context context) { | |
super(context); | |
} | |
public void setHeightRatio(double ratio) { | |
if (ratio != mHeightRatio) { | |
mHeightRatio = ratio; | |
requestLayout(); | |
} | |
} | |
public double getHeightRatio() { | |
return mHeightRatio; | |
} | |
@Override | |
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { | |
if (mHeightRatio > 0.0) { | |
int width = MeasureSpec.getSize(widthMeasureSpec); | |
int height = (int) (width * mHeightRatio); | |
setMeasuredDimension(width, height); | |
} | |
else { | |
super.onMeasure(widthMeasureSpec, heightMeasureSpec); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment