Skip to content

Instantly share code, notes, and snippets.

@gibson-khs
Last active November 28, 2017 08:28
Show Gist options
  • Select an option

  • Save gibson-khs/9e758d54f712c230227051f4092f940d to your computer and use it in GitHub Desktop.

Select an option

Save gibson-khs/9e758d54f712c230227051f4092f940d to your computer and use it in GitHub Desktop.
Android/RatioFrameLayout
<resources>
<declare-styleable name="RatioFrameLayout">
<attr name="frame_width_ratio" format="integer" />
<attr name="frame_height_ratio" format="integer" />
<attr name="frame_width_standards" format="boolean" />
</declare-styleable>
</resources>
public class RatioFrameLayout extends FrameLayout {
private int widthRatio;
private int heightRatio;
private boolean widthStandards;
public RatioFrameLayout(Context context) {
super(context);
}
public RatioFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RatioFrameLayout);
widthRatio = typedArray.getInt(R.styleable.RatioFrameLayout_frame_width_ratio, 0);
heightRatio = typedArray.getInt(R.styleable.RatioFrameLayout_frame_height_ratio, 0);
widthStandards = typedArray.getBoolean(R.styleable.RatioFrameLayout_frame_width_standards, true);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (widthRatio != 0 && heightRatio != 0) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
int splitValue;
if (widthStandards) {
splitValue = width / widthRatio;
height = splitValue * heightRatio;
} else {
splitValue = height / heightRatio;
width = splitValue * widthRatio;
}
super.onMeasure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment