2

为什么我要android:layout_width="0px"在使用ndroid:layout_weight属性时放置?例如下面是我的 main.xml 文件,我使用了android:layout_width="wrap_content",一切正常,那么为什么android:layout_width="0px"在我使用 layout_weight 属性时应该使用呢?

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:orientation="horizontal">
<EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText" android:hint="enter your name"
        android:layout_weight="3"/>
<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send"
        android:id="@+id/button"
        android:layout_weight="0"/>
</LinearLayout>

这就是我的布局的样子: 在此处输入图像描述

4

3 回答 3

2

你当然不必。另外weight=0没有多大意义。该参数控制小部件占据布局中剩余weight空间的哪一部分。所以设置有效地告诉它只占用剩余的空间。如果设置,它将占用 30 px|dp + 所有剩余空间。将宽度设置为 0 可以更容易地在不同的屏幕尺寸上获得可预测的结果。width=0width=30

一种常见的模式是拥有两个width=0重量相同的小部件,以使它们在父容器内大小相等,您不需要关心实际大小(宽度或高度)。

于 2012-12-18T05:32:41.497 回答
1

布局权重本身用于根据权重属性提供适当的宽度。检查这个

该属性根据屏幕上应占用多少空间为视图分配“重要性”值。较大的权重值允许它扩展以填充父视图中的任何剩余空间。

所以eclipse建议给宽度为0px

于 2012-12-18T05:28:49.397 回答
1

layout_weight 你可以指定多个视图之间的大小比例。

例如,您有一个 Tabelview 和一个应该向布局显示一些附加信息的图像。表格应占屏幕的 3/4,图像应占屏幕的 1/4。然后将 tabelview 的 layout_weight 设置为 3,将图像的 layout_weight 设置为 1。

要让它工作,您还必须将高度或宽度设置为 0px。

http://developer.android.com/guide/topics/ui/declaring-layout.html#CommonLayouts

于 2012-12-18T05:38:40.680 回答