【Android 開發筆記】weight屬性

來源:互聯網
上載者:User

標籤: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屬性

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.