Last active
December 27, 2015 04:39
-
-
Save lesleh/7268816 to your computer and use it in GitHub Desktop.
Implementation of onMeasure to ensure a square 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
@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