Center multiple items in a RelativeLayout without putting them in a container?

android, xml

Solution

`android:gravity` will align the content inside the `view` or `layout` it is used on.

`android:layout_gravity` will align the `view` or `layout` inside of his parent.

So adding

android:gravity="center"

to your RelativeLayout should do the trick...

Like this:

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:layout_marginTop="15sp">

</RelativeLayout>

Problem

I have a RelativeLayout containing a pair of side-by-side buttons, which I want to be centered within the layout. I could just put the buttons in a LinearLayout and center that in the RelativeLayout, but I want to keep my xml as clean as possible. Here's what I tried, this just puts the "apply" button in the center and the "undo" button to the left of it: ``` <RelativeLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="15sp"> <TextView android:id="@+id/instructions" android:text="@string/instructions" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="15sp" android:layout_centerHorizontal="true" /> <Button android:id="@+id/apply" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="@string/apply" android:textSize="20sp" android:layout_below="@id/instructions" /> <Button android:id="@+id/undo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="@string/undo" android:textSize="20sp" android:layout_toLeftOf="@id/apply" android:layout_below="@id/instructions" /> </RelativeLayout> ```

Original source

Related problems