在使用linearlayout的時候,子控件可以設置layout_weight。layout_weight的作用是設置子空間在linearlayout的重要度(控件的大小比重)。layout_weight的值越低,則控件越重要。若不設置layout_weight則默認比重為0。
如果在一個linearlayout里面放置兩個button,button1和button2,button1的layout_weight設置為1,button2的layout_weight設置為2,且兩個button的layout_width都設置為fill_parent。
復制代碼 代碼如下:
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="button1"/>
<button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="button2"/>
</linearlayout>
則button1占據屏幕寬度的三分之二,而button2占據三分之一,如下圖所示:
如果兩個button的layout_width都設置成wrap_content,則情況剛好相反。button1占三分之一,button2占三分之二,如下圖所示:
layout_weight在使用linearlayout設計復雜的布局時還是挺有用處的,例如,在水平的線性布局中,你要分足夠的空間給控件1,剩下的空間則分配給控件2,則只要設置控件1的layout_width設置為wrap_content,不用設置layout_weight,而在控件2中,設置layout_width為fill_parent,layout_weight為1即可實現。