Android Layout Weight 属性原理及正确用法
如下代码所示,会出现什么现象?
<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。
这里以水平方向为例:
该控件所占的宽度 = 该控件原宽度 + (父控件总宽度 - 已有控件总宽度) * 比例 即 该控件原宽度 + 剩余宽度 * 比例




