Android 布局权重 :How to explain the calculation of proportion when width set 'match_parent'

标签 android layout android-layout-weight

我是 android 的新手。在了解布局的 'weight' 属性时,我感到困惑。
我知道当layout_width设置为0dp时,每个元素都会占用weight/weightSum。 但是当 layout_width 设置为 ma​​tch_parrent(虽然不推荐),它有点复杂。
有人说公式是:

delta = 1-numOfElement;
proportion[ i ] = 1+delta*(weight[ i ]/weightSum);

我举个例子说清楚~

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <EditText 
        android:id="@+id/edit_message"
        android:layout_width="match_parent"
        android:layout_weight="2"
        android:layout_height="wrap_content"
        android:hint="@string/edit_message" />

    <Button
        android:text="@string/button_cancel"
        android:layout_weight="3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="sendMessage"/>
    <Button
        android:text="@string/button_send"
        android:layout_weight="4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

有3个元素,所以delta=1-3=-2;
权重总和=(2+3+4)=9;
比例[ 0 ] = 1+(-2)(2/9)=5/9;
比例[ 1 ] = 1+(-2)
(3/9)=3/9;
比例[2]=1+(-2)*(4/9)=1/9;

So it's actually 5:3:1

但是我不明白是什么意思,谁能解释一下?~
或者公式有误,请指正~谢谢

最佳答案

如果LinearLayout中有2个 View ,第一个的layout_weight为1,第二个的layout_weight为2且没有指定weightSum,默认情况下,weightSum计算为3(权重之和children),第一个 View 占空间的 1/3,第二个占 2/3。

但是,如果我们将 weightSum 指定为 5,则第一个将占用 1/5 的空间,而第二个将占用 2/5。因此,布局将占用总共 3/5 的空间,其余空间为空。

Calculation to assign any Remaining/Extra space between child. (not the total space)

space assign to child = (child individual weight) / (sum of weight of every child in Linear Layout)

如果任何一个子项的权重为 0,则它占用渲染所需的最小空间,其余可用空间按上述公式分配给子项

反向扩展发生在你的案例中,因为: 因为您使用 match_parent 作为 layout_width。权重用于分配剩余的空白空间,并且您的第一个元素与父元素匹配,因此它会尝试占据水平最高的空间,而剩余的较小空间则分配给其他两个子元素。

同样对于第二个 child ,它试图扩展到最大可用空间,为最后一个 child 留下非常少的空间,因此扩展与应用的个体权重完全相反。

换句话说, 在这种情况下,match_parent 像老板一样占主导地位。 这里没有具体的计算,而是按照顺序优先给 child 看的很清楚。

关于Android 布局权重 :How to explain the calculation of proportion when width set 'match_parent' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44179937/

相关文章:

java - Android 表单验证 - 如何防止空字段在按下按钮时导致应用程序崩溃?

Android:按下按钮时以编程方式添加 EditText

android - 如何显示长文本只显示 1 行并附加

android - 展开 View 下方的布局不可见?

android - 如何在 XML 中指定 View 的宽度和高度的百分比?

android - 如何从 windows(v10) 完全卸载 Android Studio?

android - 通过 Wifi 在 2 部 Android 手机之间发送数据

安卓 : map coordinate to a scroll-able image

html - 在 log4j 的 HTMLLayout 中获取更多信息

android - Android LinearLayout不可见