1. 程式人生 > >Android之使用weight屬性實現控件的按比例分配空間

Android之使用weight屬性實現控件的按比例分配空間

今天 text wrap 在底部 net ack 實現 sans com

從今天開始,把看書時候的知識點整理成博客,

這個比較簡單,預計有經驗的都用過,weight屬性

在做Android布局的時候,常常遇到須要幾個控件按比例分配空間的情況

比方下圖效果

技術分享

在底部設置兩個button,占領底部寬度一部分的同一時候,保持1:3的比例,

當然了,這麽難看的布局用處不大,僅是用來說明weight的使用方法

布局代碼例如以下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="6"
    android:gravity="bottom|center_horizontal" >

    <Button
        android:id="@+id/bn_main_left"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="left" />

    <Button
        android:id="@+id/bn_main_right"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:text="right" />

</LinearLayout>


當中LinearLayout裏面有個weightSum,這個屬性是用來設置LinearLayout的weight總和,

Button裏面的layout_weight就是用來設置button占領LinearLayout的空間的大小

形象一點說,LinearLayout像一個盒子,weightSum設置了盒子的大小為6,

往盒子裏放了兩個button,給左邊button設置layout_weight="1",占領1/6空間,

右邊button設置了layout_weight="3",占領3/6空間

這樣兩個button加起來占領了LinearLayout的4/6,

假設沒有給LinearLayout設置weightSum的話,則默覺得全部控件layout_weight的總和.

作者:jason0539

微博:http://weibo.com/2553717707

博客:http://blog.csdn.net/jason0539(轉載請說明出處)

Android之使用weight屬性實現控件的按比例分配空間