Skip to content

Instantly share code, notes, and snippets.

@NightlyNexus
Created August 28, 2016 06:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NightlyNexus/f58609ff53f79879c0a077efe5dd1558 to your computer and use it in GitHub Desktop.
Save NightlyNexus/f58609ff53f79879c0a077efe5dd1558 to your computer and use it in GitHub Desktop.
/*
* Copyright (C) 2016 Eric Cochran
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.content.Context;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import static android.view.View.MeasureSpec.EXACTLY;
import static android.view.View.MeasureSpec.UNSPECIFIED;
public class SquareFrameLayout extends FrameLayout {
public SquareFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@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);
float widthToHeightRatio = 1f; // Is a square.
int width;
int height;
if (widthMode == UNSPECIFIED && heightMode == UNSPECIFIED
|| widthMode != UNSPECIFIED && heightMode != UNSPECIFIED) {
if (widthSize / widthToHeightRatio > heightSize) {
// Limited by height.
width = (int) (heightSize * widthToHeightRatio);
height = heightSize;
} else {
// Limited by width.
width = widthSize;
height = (int) (widthSize / widthToHeightRatio);
}
} else if (widthMode == UNSPECIFIED) {
// Limited by height.
width = (int) (heightSize * widthToHeightRatio);
height = heightSize;
} else {
// Limited by width.
width = widthSize;
height = (int) (widthSize / widthToHeightRatio);
}
super.onMeasure(MeasureSpec.makeMeasureSpec(width, EXACTLY),
MeasureSpec.makeMeasureSpec(height, EXACTLY));
if (widthMode == EXACTLY && heightMode == EXACTLY) {
setMeasuredDimension(widthSize, heightSize);
} else if (widthMode == EXACTLY) {
setMeasuredDimension(widthSize, getMeasuredHeight());
} else if (heightMode == EXACTLY) {
setMeasuredDimension(getMeasuredWidth(), heightSize);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment