android:gravity =“center”没有按预期工作

时间:2016-02-12 18:58:31

标签: android android-layout

我有以下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>

具有以下设计。

enter image description here

button不应该垂直放置在中心吗?我知道layout_gravitygravity的工作原理。所以根据我的理解,按钮应该绝对位于水平和垂直的中心。

2 个答案:

答案 0 :(得分:6)

您必须在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>

答案 1 :(得分:0)

Based on @vspallas answer, I found the solution to my question. Basically the reason for this behavior is that I am specifying vertical orientation to my LinearLayout. It means that whatever views I place inside the layout should be shown in a vertical orientation i.e. one below the other. If I had three views inside my LinearLayout, then the result should be something like this

View1
View2
View3.

But if I did android:layout_gravity="center" for View2 and had it worked according to my expectation, then it would have placed View2 in the center, and not between View1 and View3 which will contradict the orientation attribute. Hence Android allows to set gravity to the parent itself which will make sure that all the views inherit the same gravity and are in the same orientation for LinearLayout.