如下代码所示,会出现什么现象?

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

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="#ff00ff"
            android:text="first" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:background="#ff0000"
            android:text="second" />
    </LinearLayout>

咦?怎么会出现这种情况?不是first占比是1/3吗?second占比是2/3吗?还有不是应该layout_width不是应该设置为0dp吗?

这现象怎么回事??

的确应该设置为0dp,下面就来解释一下为什么会出现这个奇怪的现象

被设置的weight值的控件,宽度应该为该控件的宽度+父控件的剩余空间*比例

水平方向的线性布局中:使用weight时,需注意将宽度设置为0dp

垂直方向的线性布局中:使用weight时,需注意将高度设置为0dp

这里以水平方向为例:

该控件所占的宽度=该控件原宽度+(父控件总宽度-已有控件总宽度)*比例

即 该控件原宽度+剩余宽度*比例

first的宽度:match_parent(原宽度) + (match_parent-(match_parent+match_parent)) * 1/3

如果不好理解,那么设match_parent为a

因为first和second空间的原有宽度都是match_parent,所以已有控件宽度是2a

first的宽度为:a+(a-2a)*1/3=2/3a

所以first的宽度为父控件的2/3,即占父控件的2/3

second的宽度为:a+(a-2a)*2/3=1/3a

所以second的宽度为父控件的1/3,即占父控件的1/3

==============================================

要达到目的,就必须将layout_width应该设置为0dp,这样first宽度就是0+(match_parent-(0+0))*1/3=1/3*match_parent

second宽度就是0+(match_parent-(0+0))*2/3=2/3*match_parent

正确设置之后

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

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="#ff00ff"
            android:text="first" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:background="#ff0000"
            android:text="second" />
    </LinearLayout>

垂直方向以此类推可得出结果。

这个“权重”属性仅仅在LinearLayout使用,在RelativeLayout没有这个属性。

 

容易出现的考题如下:

如这张图所示:

左边的代码会出现右上角的现象,文本的基线对齐导致出现了我们不想要的结果,那么就在LinearLayout中加上属性android:baselineAligned="false"

 

当只有一个TextView时,如何将其占据宽度的一半呢?

可以将其LinearLayout中添加android:weightSum=“2”,总权重为2,然后TextView的权重为1就可以达到效果。

 

===============================Talk is cheap, show me the code=============================