標籤:android style blog http color os io 使用 ar
混合使用weightSum和layout_weight
先看效果,button佔據螢幕寬度的一半。
再看開發文檔中的描述。
“定義weight總和的最大值。如果未指定該值,以所有子視圖的layout_weight屬性的累加值作為總和的最大值。一個典型的案例是:通過指定子視圖的layout_weight屬性為0.5,並設定LinearLayout的weightSum屬性為1.0,實現子視圖佔據可用寬度的50。”
XML檔案的源碼。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ffffff" android:gravity="center" android:orientation="horizontal" android:weightSum="1" > <Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="0.5" android:text="@string/activity_main_click_me" /></LinearLayout>
指定Button的android:layout_width屬性為0dp,因此需要根據android:weightSum屬性決定Button的width。
假設有一個寬度是200dp,android:weightSum屬性是1.0的LinearLayout。在這個LinearLayout中的Button寬度的計算公式如下。
Button‘s width + Button‘s weight * 200 / sum(weight)
指定Button的width為0dp,weight為0.5,sum(weight)等於1,那麼結果如下。
0 + 0.5 * 200 / 1 = 100
概要
當需要根據比例分配布局可用空間的時候,使用LinearLayout的weight屬性是很有必要的,這避免了使用硬式編碼方式帶來的副作用。如果目標平台是Honeycomb並且使用Fragment,那麼大多數案例中都是使用weight在布局檔案轉哦給你為Fragment分配空間。深入理解如何使用weight會為開發人員增添一項重要技能。
外部連結
http://developer.android.com/reference/android/widget/LinearLayout.html
http://mobile.51cto.com/abased-375428.htm
【Android 開發筆記】weight屬性