1.剩余空间为负值时layout_weight的理解
<?xml version="1.0" encoding="UTF-8" ?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:background="#ccc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="30sp" />
<TextView
android:background="#aaa"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textSize="30sp" />
<TextView
android:background="#999"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="3"
android:textSize="30sp" />
</LinearLayout>
当三个 TextView 的宽度都设为 wrap_content 的时候,比例是能够按照 layout_weight 分配的。原因是系统先给3个TextView分配他们的宽度值wrap_content(宽度足以包含他们的内容即可,此时TextView无内容),然后会把剩下来的屏幕空间按照1:2:3的比列分配给3个TextView,所以就出现了上面的效果。
2.我们再试试,把 wrap_content 换成 fill_parent 看看(为了方便查看,我们把 layout_weight 分别改为 1 2 2)。效果就成这样了(比例3 1 1):
为什么呢?
系统先给3个 TextView 分配他们所要的宽度 fill_parent,也就是说每一都是填满他的父控件,这里就是屏幕的宽度。那么这时候的
剩余空间=1 parent_width - 3 parent_width = -2 parent_width
(parent_width指的是屏幕宽度)
那么第一个 TextView 的实际所占宽度应该是 fill_parent 的宽度,即 parent_width + 他所占剩余空间的权重比列 1/5 * 剩余空间大小(-2 parent_width)=3/5parent_width
同理第二个TextView的实际所占宽度为parent_width + 2/5*(-2parent_width)=1/5parent_width;
第三个TextView的实际所占宽度为parent_width + 2/5*(-2parent_width)=1/5parent_width;所以就是3:1:1的比列显示了。
大概就是这样。
Google 官方推荐,当使用 layout_weight 属性时,可以将 width 设为 0dp,效果跟设成 wrap_content 是一样的。这样 layout_weight 就可以理解为占比了。
3.Google 官方推荐,当使用 layout_weight 属性时,可以将 width 设为 0dp,效果跟设成 wrap_content 是一样的。这样 layout_weight 就可以理解为占比了。
<?xml version="1.0" encoding="UTF-8" ?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:background="#ccc"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="30sp" />
<TextView
android:background="#aaa"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textSize="30sp" />
<TextView
android:background="#999"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:textSize="30sp" />
</LinearLayout>
文章转自: 现代魔法学院