0

The output for the following XML code-

<?xml version="1.0" encoding="utf-8"?>
<!-- layout_gravity example -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="200px"
        android:layout_graviy="center"
        android:background="@color/purple_200"
        android:orientation="horizontal">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="100px"
            android:layout_gravity="center"
            android:background="@color/purple_700"
            android:textColor="@color/white"
            android:text="@string/hello" />
    </LinearLayout>
</LinearLayout>

The light purple area, has android:layout_gravity="center", but is still appearing on the top of the outer LinearLayout. Isn't android:layout_gravity="center" supposed to position the View or Layout in the center of its parent layout? I cannot understand why that's not the case here, while the dark purple area which is a TextView is positioning itself correctly on the use of android:layout_gravity="center".

jenny jenkins
  • 95
  • 1
  • 9

1 Answers1

2

First thing, there's a TYPO, you've written graviy instead of gravity in the child LinearLayout fixing which will center this layout Horizontally.

Second, if you want to center this child LinearLayout vertically and Horizontally too, then no need of setting android:layout_gravity in this one, instead set android:gravity="center" in the root LinearLayout, it will make this centered vertically and Horizontally.

Lalit Fauzdar
  • 5,953
  • 2
  • 26
  • 50