【发布时间】: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 个视图时它变得更加复杂。
- 有没有更好的方法来实现这个目标?
- 以及为什么使用 match_parent 时权重的作用不同?
【问题讨论】:
标签: java android xml android-studio android-layout-weight