android:layout_weight权重使用
在布局中Layout_weight属性的作用:它是用来分配属于空间的一个属性,你可以设置它所占据屏幕的权重。
Layout_weight的计算公式:实际宽度 = 控件原来的长度 + 剩余空间所占百分比的宽度。
理论上控件标签的权重值越大,所分配的宽度越大,但是有时候不是,权重值越大,所分配的宽度比例反倒越小。
我们可以设置android:layout_width为wrap_content和match_parent来看测试效果,这2种情况会造成两种截然相反的效果:
1、设置 layout_width="match_parent":
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@android:color/black"
android:text="111"
android:textSize="20sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:background="@android:color/holo_green_light"
android:text="222"
android:textSize="20sp" />
</LinearLayout>
效果图:
设置的权重值和实际宽度划分成反比了,111所在的文本显示我们想占有1/3的比例,结果却占有了2/3的空间。
2、再看设置 layout_width="wrap_content":
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@android:color/black"
android:text="111"
android:textSize="20sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:background="@android:color/holo_green_light"
android:text="222"
android:textSize="20sp" />
</LinearLayout>
效果图:
这个时候得到的结果和我们预期的一样,正常了,111的文本占用了我们预期的1/3的空间。
android:layout_weight的真实含义是:一旦View设置了该属性(假设有效的情况下),那么该 View的宽度等于原有宽度(android:layout_width)加上剩余空间的占比!
设屏幕宽度为L,在两个view的宽度都为match_parent的情况下,原有宽度为L,两个的View的宽度都为L,那么剩余宽度为L-(L+L) = -L, 左边的View占比三分之一,所以总宽度是L+(-L)*1/3 = (2/3)L.事实上默认的View的weight这个值为0,一旦设置了这个值,那么所在view在绘制的时候执行onMeasure两次的原因就在这。
所以,如果想要权重和预期一样,layout_width可以设置成wrap_content,或者设置成0dp,即可。