我有以下xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="100dp"
android:orientation="vertical"
android:background="#ff0000">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00ff00"
android:text="Button"
android:layout_gravity="center"/>
</LinearLayout>
</LinearLayout>它有以下设计。

button不应该垂直放置在中间吗?我知道layout_gravity和gravity是如何工作的。因此,根据我的理解,按钮应该是绝对在中心,无论是水平的还是垂直的。
发布于 2016-02-12 19:02:53
必须在android:gravity="center"中添加LinearLayout
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="100dp"
android:orientation="vertical"
android:gravity="center"
android:background="#ff0000">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00ff00"
android:text="Button"
android:layout_gravity="center"/>
</LinearLayout>
发布于 2016-02-12 19:23:18
基于@vspallas的答案,我找到了我的问题的解决方案。基本上,这种行为的原因是,我将vertical定向指定为LinearLayout。这意味着,我在layout中放置的任何视图都应该以垂直方向显示,即位于另一个下方的视图。如果我的LinearLayout中有三个视图,那么结果应该是这样的
View1
View2
View3.但是,如果我为View2做了View2,如果它按照我的预期工作,那么它将把View2放在中间,而不是在View1和View3之间,这将与orientation属性相矛盾。因此,Android允许将重力设置到父视图本身,这将确保所有视图都继承相同的重力,并且对LinearLayout具有相同的方向。
https://stackoverflow.com/questions/35370219
复制相似问题