开发者

LinearLayout in Square Form

is it possible to have a LinearLayout inside a LinearLayout with equal height and width dynamically? i don't want 开发者_开发百科to specify the values, just that the height is the same size of the possible width.

thx


I have the same problem and i couldn't find a way to solve this using only xml. So i wrote custom layout and reference 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 reference it in xml like this

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

If there is easiest solution i'll be glad to know it.


Expanding Mojo's answer a bit to handle either height or width being the constrained 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));
}


Check out SquareLayout, an Android Library which provides a wrapper class for different Layouts, rendering them Squared dimensioned without losing any core functionalities.

The dimensions are calculated just before the Layout is rendered, hence there is no re-rendering or anything as such to adjust once the View is obtained.

To use the Library, add this to your build.gradle:

repositories {
    maven {
        url "https://maven.google.com"
    }
}

dependencies {
    compile 'com.github.kaushikthedeveloper:squarelayout:0.0.3'
}

Your XML will look like :

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜