【问题标题】:Layout weight with matchparent attribute具有 matchparent 属性的布局权重
【发布时间】:2026-02-01 06:05:01
【问题描述】:

我经常被告知在视图中使用 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>

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

 <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 时权重的作用不同?

【问题讨论】:

    标签: java android xml android-studio android-layout-weight


    【解决方案1】:

    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>
    

    结果

    【讨论】: