Android:layout_weight詳解
中文定義:
在一個布局組件中(例如:LinearLayout)中各個子項目的對於剩餘空間的使用權重。
預設:android:layout_weight= 0
預設情況下,配置模式以android:height 和 android:weight為標準
案例:
現在設定2個LinearLayout 個佔據一張,第一行有左右各一個按鈕,中間設定一個文本顯示框
第二行設定一個按鈕,主要是為了使第一行的文本顯示框自動擴張大小,布局檔案如下:
<?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" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <Button android:id="@+id/btn1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/com_frank_android_app_cal_zero" /> <TextView android:id="@+id/btn2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/cal_btn_numeric_shape" android:text="@string/com_frank_android_app_cal_one" /> <Button android:id="@+id/btn3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/com_frank_android_app_cal_two" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <Button android:id="@+id/btn4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/com_frank_android_app_first_btnShow" /> </LinearLayout> </LinearLayout> |
測試一:所有組件的寬度全部設定成 【warp_content】 包裹可顯示的內容,未設定任何weight屬性
結果非常簡單,如:
改變文本顯示框的大小以後,我們可以發現2號按鈕無法顯示了,這個事因為Android LinearLayout不同於Swing FlowLayout,無法顯示的控制項不會換行顯示,見:
假設我們現在希望,0號按鈕和1號按鈕在文本顯示框內容變化時候保持位置不變,可以利用weight來實施設定,請動手在TextView的設定檔中增加android:layout_weight = 1,這樣我們將會看到的顯示結果:
案例解釋(重點):
Weight並非網上很多文章所敘述的那樣(文章都過於片面),weight是指某個組件在布局中【剩餘空間】中的顯示權重,那麼所謂的剩餘空間又是什麼意思呢,其實是在沒有設定weight屬性的控制項優先顯示的情況,將未佔用的布局空間合理分配給設定過weight的組件
在上例中,0號和2號按鈕都設定了android:width=“warp_content",因此文本顯示框只能顯示在2個按鈕中的【剩餘空間】,不管寬度如何變動都不能超過這個寬度。
測試二:所有組件的寬度全部設定成 【warp_content】 包裹可顯示的內容,0號按鈕設定weight=1、文本顯示框設定weight=2,
2號按鈕不設定weight,顯示結果如:
案例解釋(重點):
首先我們可以看到,2號按鈕沒有設定過weight被優先顯示為wrap_content了,並且佔據了右側位置(為何會佔據右側,請看下面的組件載入策略),所有剩餘空間被依次分配給了0號按鈕和文本顯示框
由於文本顯示框的權重更高(2)所以佔據了剩餘空間的2/3 而0號按鈕只能使用1/3
注意:在文字框內容變動時候,0號按鈕和2號按鈕都能正常顯示。因為0號按鈕和文本顯示框只能在剩餘空間內活動,無法幹涉2號按鈕的顯示位置。
根據測試推匯出的Activity載入組建的策略:
一、主流程
開始-> 載入Activity->進入Activity生命週期->onCreate->載入layout設定檔->
載入容器組建(ViewGroup)->載入各個組件
二、組建載入流程
各組件載入完畢 -> 載入無weight屬性群組件的高度和寬度–>按weight和剩餘空間換算有weight屬性的組件的寬度或者高度(根據父容器的orientation屬性決定)-> 載入他們的寬度或者高度->顯示
提示:在版本較高的ADT中,設定了weight屬性後,ADT會給出一次提示警告建議將擁有weight屬性群組件的高度和寬度設定成0dp,因為這個組件的寬度已經不是由設定檔能決定的了
讀者可以自行按以上方法測試寬度等於match_parent的情況,結果將會與以上推論完全一致。
實際應用案例:
設計一個帶有摺疊列表的Dialog視窗,效果如下:
摺疊開啟後的效果: