我不明白如何使用这个属性。谁能多告诉我一点吗?
当前回答
顾名思义,布局权重指定了特定字段或小部件应该占据屏幕空间的数量或百分比。 如果我们在水平方向上指定权重,那么我们必须指定layout_width = 0px。 类似地,如果我们在垂直方向上指定权重,那么我们必须指定layout_height = 0px。
其他回答
http://developer.android.com/guide/topics/ui/layout-objects.html#linearlayout
Layout_weight定义了控件相对于其他控件必须获得的空间大小。
顾名思义,布局权重指定了特定字段或小部件应该占据屏幕空间的数量或百分比。 如果我们在水平方向上指定权重,那么我们必须指定layout_width = 0px。 类似地,如果我们在垂直方向上指定权重,那么我们必须指定layout_height = 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)
文章来源
除了其他答案之外,最重要的是将布局宽度(或高度)设置为0px
android:layout_width="0px"
否则你会看到垃圾
推荐文章
- 警告:API ' variable . getjavacompile()'已过时,已被' variable . getjavacompileprovider()'取代
- 安装APK时出现错误
- 碎片中的onCreateOptionsMenu
- TextView粗体通过XML文件?
- 如何使线性布局的孩子之间的空间?
- DSL元素android.dataBinding。enabled'已过时,已被'android.buildFeatures.dataBinding'取代
- ConstraintLayout:以编程方式更改约束
- PANIC: AVD系统路径损坏。检查ANDROID_SDK_ROOT值
- 如何生成字符串类型的buildConfigField
- Recyclerview不调用onCreateViewHolder
- Android API 21工具栏填充
- Android L中不支持操作栏导航模式
- 如何在TextView中添加一个子弹符号?
- PreferenceManager getDefaultSharedPreferences在Android Q中已弃用
- 在Android Studio中创建aar文件