首页 > 解决方案 > 具有 matchparent 属性的布局权重

问题描述

我经常被告知在视图中使用 0dp,同时在 XML 中使用权重,如下所示:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/a1"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="1" />

</LinearLayout>

但是这段代码有一个问题,当我使用像按钮这样的视图时,我不能强迫它接受我给它的确切权重。

 <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/a1"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="25"
        android:text="1" />

    <Button
        android:id="@+id/a2"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="2" />

</LinearLayout>

在上面编写的代码中,第二个按钮永远不会正好是 1/26,因为默认情况下按钮本身有一些边距和填充。

但是当我使用 match_parent 作为它们的高度时,它会强制它们恰好为 1/26,并且效果很好。

但我不明白为什么第一个按钮变成 1/26 并且似乎他们交换了重量,当我使用 3 个视图时它变得更加复杂。

  1. 有没有更好的方法来实现这个目标?
  2. 为什么重量在使用 match_parent 时表现不同?

标签: javaandroidxmlandroid-studioandroid-layout-weight

解决方案


中的间距Button不是填充或边距,而是背景。如果你想删除间距,你应该改变背景Button

建议使用android:layout_height="0dp" ,因为文档layout_weight说:

指示 LinearLayout 中有多少额外空间分配给与这些 LayoutParams 关联的视图。

它说的是“额外空间”而不是“空间”。所以正确的高度应该是 0dp +“计算的额外空间”

这里有一些示例代码

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="6"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <Button
        android:id="@+id/a1"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="@color/red"
        android:text="1" />

    <Button
        android:id="@+id/a2"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="2"
        android:background="@color/blue"
        android:text="2" />

    <Button
        android:id="@+id/a3"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="3"
        android:background="@color/yellow"
        android:text="3" />

</LinearLayout>

和结果

在此处输入图像描述


推荐阅读