我不明白如何使用这个属性。谁能多告诉我一点吗?


当前回答

附加:

对于垂直方向,不要忘记设置高度为0dp

android:layout_height="0dp"

对于水平方向,不要忘记设置宽度为0dp

android:layout_width="0dp"

其他回答

附加:

对于垂直方向,不要忘记设置高度为0dp

android:layout_height="0dp"

对于水平方向,不要忘记设置宽度为0dp

android:layout_width="0dp"

除了其他答案之外,最重要的是将布局宽度(或高度)设置为0px

android:layout_width="0px"

否则你会看到垃圾

结合以下两个答案

Flo, rptwsthi和roetzi,

记住要改变你的layout_width=0dp/px,否则layout_weight行为将会相反,最大的数字占据最小的空间,最小的数字占据最大的空间。

此外,一些权重组合会导致一些布局无法显示(因为它过度占用空间)。

当心这一点。

layout_weight tells Android how to distribute your Views in a LinearLayout. Android then first calculates the total proportion required for all Views that have a weight specified and places each View according to what fraction of the screen it has specified it needs. In the following example, Android sees that the TextViews have a layout_weight of 0 (this is the default) and the EditTexts have a layout_weight of 2 each, while the Button has a weight of 1. So Android allocates 'just enough' space to display tvUsername and tvPassword and then divides the remainder of the screen width into 5 equal parts, two of which are allocated to etUsername, two to etPassword and the last part to bLogin:

<LinearLayout android:orientation="horizontal" ...>

    <TextView android:id="@+id/tvUsername" 
    android:text="Username" 
    android:layout_width="wrap_content" ... />

    <EditText android:id="@+id/etUsername"
    android:layout_width="0dp"
    android:layout_weight="2" ... />

    <TextView android:id="@+id/tvPassword"
    android:text="Password"
    android:layout_width="wrap_content" />

    <EditText android:id="@+id/etPassword"
    android:layout_width="0dp"
    android:layout_weight="2" ... />

    <Button android:id="@+id/bLogin"
    android:layout_width="0dp"
    android:layout_weight="1"
    android:text="Login"... />

</LinearLayout>

它看起来是这样的: 而且

http://developer.android.com/guide/topics/ui/layout-objects.html#linearlayout

Layout_weight定义了控件相对于其他控件必须获得的空间大小。