我经常在Android文档中读到这个有趣的权重值。 现在我想第一次尝试一下,但它根本不行。

我从文档中了解到这样的布局:

  <LinearLayout
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:orientation="horizontal">

     <Button
        android:text="Register"
        android:id="@+id/register"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dip"
        weight="1" />

     <Button
        android:text="Not this time"
        android:id="@+id/cancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dip"
        weight="1" />

  </LinearLayout>

应该创建两个水平对齐的按钮,并平等地共享空间。问题是这两个按钮不能填满空间。

我希望按钮增长,并填满整个行。如果两个按钮都设置为匹配父按钮,则只显示第一个按钮并填充整行。


当前回答

也许将两个按钮的layout_width属性设置为“fill_parent”就可以了。

我刚刚测试了这段代码,它在模拟器中工作:

<LinearLayout android:layout_width="fill_parent"
          android:layout_height="wrap_content">

    <Button android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="hello world"/>

    <Button android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="goodbye world"/>

</LinearLayout>

确保在两个按钮上都将layout_width设置为“fill_parent”。

其他回答

另外,你需要添加这个android:layout_width="0dp"为儿童视图[按钮视图]的LinerLayout

你必须这样写:为我工作

<LinearLayout
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:orientation="horizontal"
            android:weightSum="2">

         <Button
            android:text="Register"
            android:id="@+id/register"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dip"
            android:layout_weight="1" />

         <Button
            android:text="Not this time"
            android:id="@+id/cancel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dip"
            android:layout_weight="1" />

它的android: layout_weight。权重只能在线性布局中使用。如果线性布局的方向是垂直的,那么使用android:layout_height="0dp",如果方向是水平的,那么使用android:layout_width ="0dp"。它会完美工作的。

也许将两个按钮的layout_width属性设置为“fill_parent”就可以了。

我刚刚测试了这段代码,它在模拟器中工作:

<LinearLayout android:layout_width="fill_parent"
          android:layout_height="wrap_content">

    <Button android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="hello world"/>

    <Button android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="goodbye world"/>

</LinearLayout>

确保在两个按钮上都将layout_width设置为“fill_parent”。

这张图片总结了线性布局。

您可以点击此链接获取有关该主题的更多信息。只是数学-视图,视图组和布局

视频教程线性布局:宽度,高度和权重

Android线性布局教程