2

I am testing LinearLayout and create a LinearLayout with 2 TextViews. the LinearLayout has the attribute gravity="center_vertical", and the first TextView within the LinearLayout has attribute layout_gravity="top".

gravity="center_vertical" of LinearLayout puts its content in center vertically.

layout_gravity="top" of TextView tells its container to put me on the top.

So what happened if they are together?

In my experiment, the 'layout_gravity="top"' does not work.

following is my code and result:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical">
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="top"
    android:text="textview 1"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="textview 2"/>

</LinearLayout>

My result

Nissa
  • 4,589
  • 8
  • 27
  • 37
karon
  • 21
  • 1

2 Answers2

0

Most probably, the parent element's gravity is the first to be executed. You can't see the effect of layout_gravity top because it follows the gravity set to its parent element. You should not set gravity center_vertical to linearlayout if you don't want the first textview to appear at the middle.

0

What Jay Bryant Casilang is somewhat correct. It is because of parent's gravity. But there is more. It is also because it is a LinearLayout.

https://developer.android.com/guide/topics/ui/layout/linear.html

A LinearLayout designed for views to be "next" to each other, either vertically or horizontally. Because you are setting android:gravity="center_vertical" on the LinearLayout and android:layout_gravity="top" on the first TextView, what you are hoping to see is this:

enter image description here

However, this would mean that there would be spacing between the two layouts. Spacing that is "unaccounted" for (no margins, no padding, etc.).

And THAT is NOT allowed in LinearLayout.

all children of LinearLayout has to be next to one another in some way (in a linear way, get it?)

Btw, I achieved the top like this:

<?xml version="1.0" encoding="utf-8"?>
<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="textview 1"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:text="textview 2"/>

</RelativeLayout>

Hope this was clear.

ᴛʜᴇᴘᴀᴛᴇʟ
  • 4,057
  • 5
  • 33
  • 62