bbarrett
bbarrett

Reputation: 78

center children in a custom RelativeLayout

I have defined a custom relative layout to force a square view in my layout. But I am having trouble centering the children in that relative layout.

My custom RelativeLayout is defined as follows:

public class SquareView extends RelativeLayout {

  public SquareView(Context context) {
    super(context);
  }

  public SquareView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public SquareView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
  }

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        int size;

        size = Math.min(widthSize, heightSize);
        setMeasuredDimension(size, size);

        int finalMeasureSpec = MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY);
        super.onMeasure(finalMeasureSpec, finalMeasureSpec);

    }   
}

and my xml is as follows:

<com.mypackage.SquareView
    android:id="@+id/gameboard_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerHorizontal="true"
    android:layout_centerInParent="true"
    android:gravity="center_horizontal"
    android:padding="0dp" >

    <LinearLayout
        android:id="@+id/gameboard"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerInParent="true"
        android:background="@drawable/xmlgameboard"
        android:gravity="center_horizontal"
        android:orientation="vertical" >
    </LinearLayout>
</com.mypackage.SquareView>

When I view the xml file in graphical view I see the SquareView (gameboard_container) filling all available space (not square), but the child LinearLayout (gameboard) is square.

However, the child LinearLayout (gameboard) is also left justified, where as I require it to be centered.

How would I fix this?

Thank you.

Upvotes: 1

Views: 705

Answers (1)

bbarrett
bbarrett

Reputation: 78

After 3 days of struggling with this I've managed to solve it. The solution was to simply nest my SquareView inside a frame layout. Then I could centre the SquareView using

android:layout_gravity="center_horizontal"

Upvotes: 1

Related Questions