LinearLayout in square shape

Is it possible to have a LinearLayout inside a LinearLayout with the same height and width dynamically? I don’t want to specify values, just so that the height is the same size of the possible width.

THX

+7
source share
3 answers

I have the same problem and I could not find a way to solve this problem using only xml. Therefore, I wrote a special layout and refer to it from xml.

public class SquareLayout extends LinearLayout { @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, widthMeasureSpec); // or you can use this if you want the square to use height as it basis // super.onMeasure(heightMeasureSpec, heightMeasureSpec); } } 

and link to it in xml like this

 <your.package.SqureLayout ..... </your.package.SquareLayout> 

If there is the simplest solution, I will be glad to know about it.

+16
source

Extending Mojo, answer a little to treat height or width as a limited dimension according to context:

 @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = MeasureSpec.getSize(widthMeasureSpec); int height = MeasureSpec.getSize(heightMeasureSpec); int size = Math.min(width, height); // Call super with adjusted spec super.onMeasure(MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY)); } 
+2
source

Check out SquareLayout , an Android library that provides a wrapper class for different layouts, Quadratic size without losing basic functionality.

Dimensions are calculated immediately before the layout is displayed , so there is no re-rendering or anything as such for customization after receiving the view.

To use the library, add it to your build.gradle file:

 repositories { maven { url "https://maven.google.com" } } dependencies { compile 'com.github.kaushikthedeveloper:squarelayout:0.0.3' } 

Your XML will look like this:

 <!-- Inner Linear Layout --> <com.kaushikthedeveloper.squarelayout.SquareLinearLayout android:layout_width="match_parent" android:layout_height="match_parent" /> 
0
source

All Articles