Skip to content

Instantly share code, notes, and snippets.

@scruffyfox
Last active December 15, 2015 07:59
Show Gist options
  • Select an option

  • Save scruffyfox/5227546 to your computer and use it in GitHub Desktop.

Select an option

Save scruffyfox/5227546 to your computer and use it in GitHub Desktop.
Square layout
package x.ui;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.LinearLayout;
/**
* @brief Square layout class to create layouts that adjust its width/height to achieve the 1:1 scale ratio.
*
* @code
* <x.ui.SquareLayout
* android:layout_width="fill_parent"
* android:layout_height="20dp"
* >
* <!-- content -->
* </x.ui.SquareLayout>
* @endcode
*/
public class SquareLayout extends LinearLayout
{
/**
* Default Constructor
* @param context The application's context
*/
public SquareLayout(Context context)
{
super(context);
}
/**
* Default constructor
* @param context The context of the application/activity
* @param attrs The attribute set gathered from the XML
*/
public SquareLayout(Context context, AttributeSet attrs)
{
super(context, attrs);
}
/**
* Measures the view and forces it to be square
* @param widthMeasureSpec The width spec to use when measuring
* @param heightMeasureSpec The height spec to use when measuring
*/
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
int mScale = 1;
if (width < (int) (mScale * height + 0.5))
{
width = (int) (mScale * height + 0.5);
}
else
{
height = (int) (width / mScale + 0.5);
}
super.onMeasure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment