androidandroid-layoutandroid-relativelayoutandroid-xmlandroid-gravity

Android Gravity Center in RelativeLayout Doesn't Work Like LinearLayout


For RelativeLaout:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <TextView
        android:id="@+id/a_textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:text="Sam"
        android:textColor="@color/black"
        android:textSize="30sp" />

    <TextView
        android:id="@+id/b_textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:text="Kate"
        android:textColor="@color/black"
        android:textSize="30sp"
       android:layout_toEndOf="@id/a_textView"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show"
        android:textSize="30sp"
        android:layout_toEndOf="@id/b_textView"/>

</RelativeLayout>

Result: Not centered perfectly

enter image description here

For LinearLayout:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:gravity="center">    //<- here, child Views are the same

Result: Centered perfectly

enter image description here

Question: Why so and how to make RelativeLayout to achieve the same result in LinearLayout by ONLY MODIFYING THE ATTRIBUTES IN RelativeLayout?


Solution

  • You have different solutions but changing some attributes in the children views.

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        ..>
    
        <LinearLayout
           android:orientation="horizontal"
           android:gravity="center_horizontal">
    
            <TextView/>
            <TextView/>
            <Button/>
    
        </LinearLayout>
    </RelativeLayout>
            
    

    or:

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        ..>
    
            <TextView/>
            <TextView/>
            <Button
              android:layout_alignBaseline="@id/a_textView">
    
    </RelativeLayout>
    

    enter image description here