Skip to content

Instantly share code, notes, and snippets.

@lesleh
Last active December 27, 2015 04:39
Show Gist options
  • Save lesleh/7268816 to your computer and use it in GitHub Desktop.
Save lesleh/7268816 to your computer and use it in GitHub Desktop.
Implementation of onMeasure to ensure a square aspect ratio.
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int width, height;
// If one of the measures is match_parent, use that one to determine the size.
// If not, use the default implementation of onMeasure
if(widthMode == MeasureSpec.EXACTLY && heightMode != MeasureSpec.EXACTLY) {
width = height = widthSize;
if(heightMode == MeasureSpec.AT_MOST)
height = Math.min(height, heightSize);
} else if(heightMode == MeasureSpec.EXACTLY && widthMode != MeasureSpec.EXACTLY) {
width = height = heightSize;
if(widthMode == MeasureSpec.AT_MOST)
width = Math.min(width, widthSize);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}
setMeasuredDimension(width, height);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment