RelativeLayout: align View centered horizontal or vertical relative to other view

sockeqwe picture sockeqwe · May 12, 2013 · Viewed 37.7k times · Source

Is it possible to align a view in XML in a RelativeLayout centered horizontal or vertical according another already existing view.

For example: lets say there is something like this:

enter image description here

The second text view should be displayed centered below the first text view:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="72dp"
        android:text="dynamic text" />

    <TextView
        android:id="@+id/second"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/textView"
        android:layout_marginLeft="43dp" <!-- Is there a rule to center it? -->
        android:text="centered below text 1" />

</RelativeLayout>

Is is possible to implement something like that in XML? Is there a rule that i have missed yet? I do not want to calculate the position programmatically

Answer

Jessicardo picture Jessicardo · Oct 15, 2014

I have a much better solution than the accepted one. NO EXTRA NESTING! You can do this by combining two attributes on the smaller view. if you are centering horizontally you can use both align_start & align_end to the bigger view. Make sure the text gravity is centered btw "android:gravity="center". For Vertical alignment use both align_top & align_bottom. below is the modified implementation of your layout.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="43dp" >

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignStart="@+id/second"
    android:layout_alignEnd="@+id/second"
    android:gravity="center"
    android:text="dynamic text" />

<TextView
    android:id="@+id/second"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/textView"
    android:gravity="center"
    android:text="centered below text 1" />

</RelativeLayout>

No need for unnecessary nesting like the accepted answer.