Qiming Chen
Qiming Chen

Reputation: 35

How to create a square layout and set it center horizontally

I want to customize a layout and make it into a square. In xml, I set the its layout_width and layout_height into 'match_parent'. And then in its onMeasure() method, I get the values of its height and width and set the shortest of them as the value of each side of square. The code is kind of like this:

<SquaredRelativeLayout
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_centerHorizontal="true"
/>

public class SquaredRelativeLayout extends RelativeLayout {
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        if(width > height) {
             super.onMeasure(heightMeasureSpec, heightMeasureSpec);
        } else {
             super.onMeasure(widthMeasureSpec, widthMeasureSpec);
        }
    }
}

Now here is my problem: I need to set this layout center horizontally of its parent. But every time when width > height, the layout will be aligned to left of its parent. Does any one how to solve this?

Upvotes: 3

Views: 3210

Answers (2)

sach
sach

Reputation: 271

Use android:gravity="center" in your parent layout.

Upvotes: 0

N.T.
N.T.

Reputation: 2611

Use android:gravity="center" in your SquaredRelativeLayout's parent

or

use android:layout_centerInParent="true" in your SquaredRelativeLayout (instead of android:layout_centerHorizontal="true")

Upvotes: 2

Related Questions