我不明白如何使用这个属性。谁能多告诉我一点吗?
当前回答
结合以下两个答案
Flo, rptwsthi和roetzi,
记住要改变你的layout_width=0dp/px,否则layout_weight行为将会相反,最大的数字占据最小的空间,最小的数字占据最大的空间。
此外,一些权重组合会导致一些布局无法显示(因为它过度占用空间)。
当心这一点。
其他回答
使用layout_weight,你可以指定多个视图之间的大小比例。例如,你有一个MapView和一个表,它应该显示一些额外的信息到地图。地图应该使用屏幕的3/4,表格应该使用屏幕的1/4。然后将映射的layout_weight设置为3,将表的layout_weight设置为1。
为了让它工作,你还必须设置高度或宽度(取决于你的方向)为0px。
除了其他答案之外,最重要的是将布局宽度(或高度)设置为0px
android:layout_width="0px"
否则你会看到垃圾
layout_weight tells Android how to distribute your Views in a LinearLayout. Android then first calculates the total proportion required for all Views that have a weight specified and places each View according to what fraction of the screen it has specified it needs. In the following example, Android sees that the TextViews have a layout_weight of 0 (this is the default) and the EditTexts have a layout_weight of 2 each, while the Button has a weight of 1. So Android allocates 'just enough' space to display tvUsername and tvPassword and then divides the remainder of the screen width into 5 equal parts, two of which are allocated to etUsername, two to etPassword and the last part to bLogin:
<LinearLayout android:orientation="horizontal" ...>
<TextView android:id="@+id/tvUsername"
android:text="Username"
android:layout_width="wrap_content" ... />
<EditText android:id="@+id/etUsername"
android:layout_width="0dp"
android:layout_weight="2" ... />
<TextView android:id="@+id/tvPassword"
android:text="Password"
android:layout_width="wrap_content" />
<EditText android:id="@+id/etPassword"
android:layout_width="0dp"
android:layout_weight="2" ... />
<Button android:id="@+id/bLogin"
android:layout_width="0dp"
android:layout_weight="1"
android:text="Login"... />
</LinearLayout>
它看起来是这样的: 而且
简而言之,layout_weight指定了布局中要分配给View的额外空间的多少。
线性布局支持为各个子节点分配权重。此属性为视图分配了一个“重要性”值,并允许它展开以填充父视图中的任何剩余空间。视图的默认权重为0。
计算子节点之间的剩余空间
一般情况下,公式为:
分配给孩子的空间=(孩子的个人体重)/(线性布局中每个孩子的体重之和)
示例1
如果有三个文本框,其中两个声明权重为1,而第三个文本框没有权重(0),那么剩余空间的分配如下:
第一个文本框= 1/(1+1+0) 第二个文本框= 1/(1+1+0) 第三个文本框= 0/(1+1+0)
示例2
假设在水平行中有一个文本标签和两个文本编辑元素。标签没有指定layout_weight,因此它占用呈现所需的最小空间。如果这两个文本编辑元素的layout_weight都设置为1,父布局中的剩余宽度将在它们之间平均分配(因为我们声称它们同样重要)。
计算:
第一个标签= 0/(0+1+1) 第二个文本框= 1/(0+1+1) 第三个文本框= 1/(0+1+1)
如果第一个文本框的layout_weight为1,第二个文本框的layout_weight为2,那么剩余空间的三分之一将给第一个文本框,三分之二给第二个文本框(因为我们声称第二个文本框更重要)。
计算:
第一个标签= 0/(0+1+2) 第二个文本框= 1/(0+1+2) 第三个文本框= 2/(0+1+2)
文章来源
那样想的话,会简单些
如果你有3个按钮,它们的权重分别为1,3,1,它将像HTML中的表格一样工作
为这一行提供5份:1份用于按钮1,3份用于按钮2,1份用于按钮1
方面,
推荐文章
- 改变开关的“开”色
- 以编程方式将EditText的输入类型从PASSWORD更改为NORMAL,反之亦然
- 如何在隐藏和查看密码之间切换
- 在Android上调整一个大的位图文件到缩放输出文件
- 如何更改Android版本和代码版本号?
- Android Studio突然无法解析符号
- 应用程序重新启动而不是恢复
- 如何设置整个应用程序在纵向模式?
- Android中文本的阴影效果?
- 以编程方式设置TextView的布局权重
- Android -如何覆盖“后退”按钮,所以它不完成()我的活动?
- 如何从通知点击发送参数到一个活动?
- 导航目标xxx对于这个NavController是未知的
- 使用ConstraintLayout均匀间距的视图
- 文件google-services错误。模块根文件夹中缺少Json。谷歌服务插件没有它就不能正常工作。