Search code examples
androidandroid-layoutandroid-fragmentsandroid-relativelayout

layout_centerInParent in a RelativeLayout doesn't center on emulator or device


I have a fragment with this layout:

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="My Fragment"
        android:textSize="30sp"
        android:layout_centerInParent="true"/>
</RelativeLayout>

In Android Studio preview, I'm seeing this:

Enter image description here

Which is fine, but on the emulator or on a real device I see:

Enter image description here

What am I missing? How do I center that text in the parent?

The parent layout is the FrameLayout:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:id="@+id/toolbar"/>

    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/frame_layout">

    </FrameLayout>
</LinearLayout>

Solution

  • You need to change width of your FrameLayout

    Change your FrameLayout width to android:layout_width="match_parent"

    SAMPLE CODE

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    
        <android.support.v7.widget.Toolbar
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:id="@+id/toolbar"/>
    
        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/frame_layout">
    
        </FrameLayout>
    </LinearLayout>