Bolton Bolton - 1 year ago 127
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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download