Android layout_weight的奇葩特性

在Android的控件佈局中,有一個奇葩的 layout_weight 屬性,定義如下:
layout_weight : 用於指定剩餘空閒空間的分割比例。用法:

<LinearLayout
  android:orientation="horizontal">

  <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_height"
      android:layout_weight="1"
      android:text="888"/>

  <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_height"
      android:layout_weight="1"
      android:text="999999"/> 
</LinearLayout>

爲什麼說是奇葩呢?
以上面的佈局代碼爲例,TextView-888 和 TextView-999999 是橫向排列的2個控件,它們的layout_weight=”1”,說明這2個控件平分了所在LinearLayout的剩餘的空閒空間, 我們很容易的就誤認爲這2個控件平分了水平方向的空間,即:各自佔據了 50% 的寬度。
其實這是錯誤的,而是:TextView-999999控件所佔據的寬度 > TextView-888所佔據的寬度。因爲999999字符佔據的寬度大於888佔據的寬度,即:w(999999) + 1/2空閒空間 > w(888) + 1/2空閒空間。
這就是它奇葩的地方,很容易就讓我們一直誤認爲是整個控件分割空間。到這裏,大家一定會認爲,這樣的話,layout_weight 這個屬性就沒有什麼意義了,原以爲它可以分配空間呢,原來只是分割剩餘空閒空間。
其實,layout_weight 是可以用來進行整個空間的分割的,如果我們讓控件的寬度定義爲0,這樣比如2個控件的 layout_weight=”1” 就可以各自50%平分整個空間了,因爲:0 + 1/2空閒空間 = 0 + 1/2空閒空間
這是一個小技巧,也是非常實用的一個實用layout_weight分割方案:定義控件的 layout_width=”0dp” 或 layout_height=”0dp” 配上 layout_weight 就可以實現對整個空間的比例分割了。
下面定義了2個控件的 layout_width=”0dp”, layout_weight=”1”,實現了水平方向50%平均分割:

<LinearLayout
  android:orientation="horizontal">

  <TextView
      android:layout_width="0dp"
      android:layout_height="wrap_height"
      android:layout_weight="1"
      android:text="888"/>

  <TextView
      android:layout_width="0dp"
      android:layout_height="wrap_height"
      android:layout_weight="1"
      android:text="999999"/>

</LinearLayout>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章