Skip to content

Instantly share code, notes, and snippets.

@umarhussain15
Created August 30, 2017 11:11
Show Gist options
  • Save umarhussain15/33c659113a0db5d13073adf065283f2c to your computer and use it in GitHub Desktop.
Save umarhussain15/33c659113a0db5d13073adf065283f2c to your computer and use it in GitHub Desktop.
Making square relative layouts based on height or width of layout.
<SquareRelativeLayoutByHeight xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content>
</SquareRelativeLayoutByHeight>
<!-- similarly SquareRelativeLayoutByWidth can be used -->
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.RelativeLayout;
/**
* A RelativeLayout that will always be square -- same width and height,
* where the width is based off the height.
*/
public class SquareRelativeLayoutByHeight extends RelativeLayout {
public SquareRelativeLayoutByHeight(Context context) {
super(context);
}
public SquareRelativeLayoutByHeight(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SquareRelativeLayoutByHeight(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public SquareRelativeLayoutByHeight(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// Set a square layout based on height value
super.onMeasure(heightMeasureSpec, heightMeasureSpec);
}
}
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.RelativeLayout;
/**
* A RelativeLayout that will always be square -- same width and height,
* where the height is based off the width.
*/
public class SquareRelativeLayoutByWidth extends RelativeLayout {
public SquareRelativeLayoutByWidth(Context context) {
super(context);
}
public SquareRelativeLayoutByWidth(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SquareRelativeLayoutByWidth(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public SquareRelativeLayoutByWidth(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// set square layout based on width value
super.onMeasure(widthMeasureSpec, widthMeasureSpec);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment