Search code examples
androidelementcenterandroid-relativelayout

How can I center a relatively sized element in an Android app?


If I am using:

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:weightSum="1.0"
    android:background="@drawable/mainpgbg">
<RelativeLayout
    android:layout_width="0dip"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_weight="0.50"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_gravity="center_horizontal">
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Log In"
            android:textSize="24sp"
            android:id="@+id/logInBtn"
            android:layout_gravity="center_vertical"
            android:layout_weight="0.50"
            android:background="@drawable/round"
            android:padding="20dp"
            android:layout_marginBottom="128dp"
            android:layout_alignParentBottom="true" />
</RelativeLayout>
</LinearLayout>

I anticipated that the RelativeLayout would be displayed centered on the screen, but it seems that you need a RelativeLayout to center elements, however you need a LinearLayout to create relative size elements.

How can I do both? Center a relatively sized element?


Solution

  • Add android:gravity="center" to your LinearLayout's xml to center its children (anything inside of it):

    <LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:weightSum="1.0"
    android:background="@drawable/mainpgbg"
    android:gravity="center">