Bolton Bolton - 1 month ago 20
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

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:

@Override
public void onResume(){
    super.onResume();
    findViewById(R.id.squareView).getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override public void onGlobalLayout() {
            View squareView = findViewById(R.id.squareView);
            LayoutParams layout = squareView.getLayoutParams();
            layout.height = squareView.getWidth();
            squareView.setLayoutParams(layout);
            squareView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        }
    });
}

Where R.id.squareView 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.