我正在测试LinearLayout并创建一个具有2个TextViews的LinearLayout。该LinearLayout具有属性gravity="center_vertical",并且LinearLayout中的第一个TextView具有属性layout_gravity="top"。
LinearLayout的gravity="center_vertical"将其内容垂直放置在中间。
TextView的layout_gravity="top"告诉它的容器把我放在最上面。
那么如果他们在一起会发生什么呢?
在我的实验中,‘layout_gravity=’top‘’不起作用。
以下是我的代码和结果:
<?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>

发布于 2016-11-04 11:58:19
最有可能的是,父元素的重力是第一个被执行的。您看不到layout_gravity顶部的效果,因为它遵循设置为其父元素的重力。如果你不想让第一个文本视图出现在中间,你不应该将重力center_vertical设置为线性布局。
发布于 2016-11-04 12:39:02
杰伊·布莱恩特·卡西朗在某种程度上是正确的。这是因为父母的引力。但还有更多的原因。这也是因为它是一个LinearLayout。
https://developer.android.com/guide/topics/ui/layout/linear.html
一个LinearLayout,设计用于视图之间的“相邻”,无论是垂直还是水平。因为您在LinearLayout上设置了android:gravity="center_vertical",在第一个TextView上设置了android:layout_gravity="top",所以您希望看到的是:

但是,这意味着两个布局之间会有间距。未说明的间距(无边距、无填充等)。
而这在LinearLayout中是不允许的。
LinearLayout的所有子级都必须以某种方式相邻(以线性方式,明白吗?)
顺便说一句,我是这样达到顶峰的:
<?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>希望你说得很清楚。
https://stackoverflow.com/questions/40414407
复制相似问题