Pieter
Pieter

Reputation: 32765

Horizontally centering all children of a RelativeLayout

I'm trying to horizontally center all children of a RelativeLayout that is vertically centered towards its parent. My initial gut feeling was to toy with the gravity of the RelativeLayout, but that just centers the layout towards its parent. Playing with the gravity of the child views triggers other undesired behavior.

Here's what happens when I adjust the gravity of the RelativeLayout:

Example

Desired behavior is that the TextView moves a little bit to the right so that it's horizontally centered relative to the screen. How do I achieve this?

Upvotes: 4

Views: 1278

Answers (2)

Nyxar
Nyxar

Reputation: 54

Here is a simple example :

<RelativeLayout 
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">

<Button
    android:id="@+id/button"
    android:layout_centerInParent="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button"/>
<TextView
    android:layout_centerInParent="true"
    android:layout_below="@id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!" />

</RelativeLayout>

Output : enter image description here

Upvotes: 0

kirtan403
kirtan403

Reputation: 7411

Adding this property to your TextView should work:

android:layout_centerHorizontal="true"

Upvotes: 2

Related Questions