在android中LinearLayout是线性布局,在线性布局中有这样一个属性,android:layout_weight。layout_weight代表的是控件所占剩余空间的比例。
什么是剩余空间
剩余空间就是总的空间大小减去控件自身的大小。例如,控件自身的大小是100dp,总的空间的大小是400dp,那么剩余空间的大小就是400-100=300dp
奇怪现象,加深理解什么是剩余空间的大小
<span style="font-size:14px;"></span><pre name="code" class="html"><?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="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#FF0000" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2"
android:background="#00FF00" />
</LinearLayout>
在Button1中我们设置了layout_weight=1,在Button2我们设置layout_weight=2;显示效果如下:
这是为什么呢,我们明明设置了button1的layout_weight=1,button2的layout_weight=2,显示的button1:button2=2:1
原因:我们button1的layout_layout=match_parent,所以button1控件自身高度所占空间是button1Height=match_parent;button2的layout_height=match_parent,所以button2控件自身所占高度是button2Height=match_parent。
两个button所占自身所占空间大小的总和是totalHeight=button1Height+button2Height=match_parent+match_parent=2*match_parent.
总的空间大小:在这里就是LinearLayout的layou_height的值,total=match_parent
剩余空间:dalta=total-totalHeight=-match_parent
button1的高度是button1Height+dalta*1/3=match_parent+(-match_parent)*1/3=2/3match_parent
button2的高度是button2Height+dalta*2/3=match_parent+(-match_parent)*2/3=1/3match_parent
是不是button1与button2的比例变成你2:1