java - 具有 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 个视图时它变得更加复杂。
- 有没有更好的方法来实现这个目标?
- 为什么重量在使用 match_parent 时表现不同?
解决方案
中的间距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>
和结果
推荐阅读
- javascript - 控制台错误“未捕获的 ReferenceError:$ 未定义”
- ansible - Rundeck 与 Ansible - 在本地执行或分派到节点?
- c# - 实例化的预制件没有按预期移动
- python - 如何让 pyspark 和 SparkSQL 在 Spark 上执行 Hive?
- android - 如何在 Kotlin 协程中使用 Sqldelight
- assembly - STR 到 ARM 程序集中标签指向的内存位置时出现分段错误
- swiftui - SwiftUI 和多个选择器
- java - 复制文件后如何释放docker的内存?
- javascript - 为什么 position().top 在第二个表中返回错误的值?
- javascript - 接下来实施中间件有错误