Bolton Bolton - 8 months ago 71
Android Question

How to set fixed aspect ratio for a layout in Android

I am trying to set the width of the layout to "fill_parent" while having the height of the view just the same length, to make the layout a square.

Any suggestions will be appreciate, thanks in advance! :D


You might try initially setting the layout_height to wrap_content. But from there I think you have to go into code. Just to experiment, in your activity try something like:

public void onResume(){
    findViewById( OnGlobalLayoutListener() {
        @Override public void onGlobalLayout() {
            View squareView = findViewById(;
            LayoutParams layout = squareView.getLayoutParams();
            layout.height = squareView.getWidth();

Where is the id of the view in question. And note, this code is wrapped in the onGlobalLayout call to ensure that squareView.getWidth() has a meaningful value.