android- layout_weight="0" 的含义

android- meaning of layout_weight="0"

我正在使用 layout_weight 指定 android 中特定 viewGroups 中各种视图的比例。
this 问题的答案中,我对 layout_weight 是什么有了清晰的概念。我使用普通数学计算 viewGroup 中所有 views 的大小(即我有 3 views of 1,2 & 3 layout_weights 并且它们都有 layout_height="0dp" 然后它们在 viewGroup 中有 1/(1+2+3), 2/(1+2+3), 3/(1+2+3) 个空格用于垂直对齐) .
但是,layout_weight="0" 是什么意思?如何确定 layout_weight="0" 的视图大小?

对于所有具有 layout_weight 的视图,必须具有 layout_height 或 layout_width 作为 0dp,具体取决于布局的方向和要求。

  1. layout_weight="1" and layout_width="0dp" ==> 如果旁边没有其他布局,该特定视图将被水平拉伸。

  2. layout_weight="0" 和 layout_width="100dp" ==> 该特定布局将按原样运行 没有 layout_weight 的含义在这种情况下。

  3. 权重的最佳用途是当您需要两个具有相同 height/width 且彼此相邻的视图时,您可以为布局和权重添加 width/height 作为“0dp”两个布局都为“1”。

layout_weight = "0" 在 xml 中不意味着应该有 android:layout_width="0dp" 所以时间如果你想为所有控件提供相同的 space在 Linarlayout 方向我们使用这个例如:- 如果我们想水平放置 3 个按钮,我们使用下面的代码

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="1">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="0.33"/>
    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="0.33"/>
    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="0.33"/>

</LinearLayout>`

所以我们放在这里

android:weightSum="1"

并在控制的权重上做相等的分配。在所有设备中,它都会以正确的方式显示,但 Imageview 除外。

For all the view which have layout_weight must have layout_height or layout_width as 0dp depending on the orientation and requirement of layout.

这是不正确的。首先,应用 "layout_width" 和 "layout_height" 参数,视图将至少为这个大小。其次,ViewGroup 中剩余的 space 将根据其权重按比例分配给视图。所以权重“0”意味着在那个阶段不会给视图一些额外的大小。