android布局重量和重力问题

时间:2016-11-19 21:16:26

标签: android android-layout

我想更好地了解android布局。在下面的例子中,我解决了我的问题,但只是通过反复试验。我想了解为什么它有效。

我在另一个布局中设置了“标题”行。我希望第一部分尽可能多地使用宽度,第二部分只使用它需要的部分。所以我将layout_1设置为权重为1,layout_2设置权重为0.最初,我同时使用了match_parent的layout_width。这导致layout_2占据整个宽度并使layout_1消失。我最后通过将layout_2的宽度设置为wrap_content来修复它。我知道layout_2有宽度wrap_content是有道理的。但是不明白为什么layout_2 match_parent在权重为0时占用整个宽度,而layout_1也有宽度match_parent。

代码示例如下。

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

<LinearLayout android:id="@+id/header_layout_1"
              android:orientation="horizontal"
              android:layout_height="wrap_content"
              android:layout_width="match_parent"
              android:layout_gravity="center"   >

    <LinearLayout android:orientation="horizontal"
                  android:layout_height="match_parent"
                  android:layout_width="match_parent"
                  android:gravity="center"
                  android:layout_weight="1">
        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="some text"/>
    </LinearLayout>

   <!-- changing width on header_layout_2 to match_parent takes over layout, wrap_content gives me what I want -->
    <LinearLayout android:id="@+id/header_layout_2"
            android:orientation="horizontal"
                  android:layout_height="match_parent"
                  android:layout_width="match_parent"
                  android:layout_weight="0">
        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="some more text"/>
    </LinearLayout>
</LinearLayout>
<!--end of header-->
</LinearLayout>
相关问题