Search code examples
androidandroid-layoutandroid-relativelayout

layout_centerHorizontal item is not centered when another view is at the right side of it


When I use layout_centerHorizontal to center an item in the view horizontally and another item is in the right side of it, it's not centered.

enter image description here

But when I delete the second item, It moves to the center.

enter image description here

This is the code:

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

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="6"
        android:gravity="center_horizontal">

    <TextView
        android:id="@+id/message"
        android:layout_width="240dp"
        android:layout_height="240dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:background="#13D372"/>

    <TextView
        android:id="@+id/message2"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_marginTop="50dp"
        android:layout_toRightOf="@id/message"
        android:background="#125632"
        />

    </RelativeLayout>

</LinearLayout>

Solution

  • Using android:gravity="center_horizontal" will place the childs (your two TextViews) in the horizontal center of its container.

    Remove android:gravity="center_horizontal" from parent and keep android:layout_centerHorizontal="true" in your child layout (TextView) to only center this one.

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="4">
    
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="6">
    
            <TextView
                android:id="@+id/message"
                android:layout_width="240dp"
                android:layout_height="240dp"
                android:layout_centerHorizontal="true"    <!--here-->
                android:layout_marginTop="50dp"
                android:background="#13D372"/>
    
            <TextView
                android:id="@+id/message2"
                android:layout_width="60dp"
                android:layout_height="60dp"
                android:layout_marginTop="50dp"
                android:layout_toRightOf="@id/message"
                android:background="#125632"
                />
    
        </RelativeLayout>
    
    </LinearLayout>