我研究了另一个stackoverflow问题//答案,发现layout_weight的有效定义是“此属性为视图分配一个“重要性”值,并允许其扩展以填充父视图中的任何剩余空间”
(来源:What does android:layout_weight mean?

我正在尝试将该概念应用于我的代码。
目前,我的代码(没有布局权重)是

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >
    <TextView
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="Home"
       android:gravity="center"
     />
    <TextView
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="About"
       android:gravity="center"
      />
</LinearLayout>


现在的布局是http://imgur.com/eq6q0I8
(房屋应占据match_parent的所有空间bc)

但是,如果我在两个文本视图中都添加了android:layout_weight =“ 1”,
我得到这个布局http://imgur.com/fscM0Zr

(两者都是可见的,并且共享相同的空间量)

我的问题是,从layout_weight的有效定义中如何发生?在此示例中,layout_weight将为两个文本视图平均分配额外的空间。但是没有多余的空间,因为第一个具有width match_parent的宽度,这将使其占据整个父对象的宽度(没有多余的空间)

最佳答案

这是怎么回事?

为了解决这个问题,我们假设LinearLayout的宽度为100px。


TextView主页的格式为MATCH_PARENT,因此100px
TextView About是MATCH_PARENT,因此100px


因此,孩子使用的总宽度为100px + 100px = 200px

现在,让我们计算剩余宽度:这是可用宽度和所有子项使用的宽度之间的差:

RemainingWidth = AvailableWidth (100px) - TotalWidthUsedByChildren (200px) = -100px

注意它是负数

有2个子视图,因此请根据其重量分配剩余宽度。在这种情况下,每个孩子都会收到剩余的50%...,这意味着每个孩子都会收到-50px。

所以最后:


TextView主页宽度为100px + -50px = 50px
TextView关于宽度为100像素+ -50像素= 50像素


完美的逻辑,但不是很直观。因此,建议在使用layout_weight时始终将填充视图的宽度设置为0。

10-06 13:14