奇葩屬性:layout_weight 的解釋及使用


摘要

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>

 

下面定義了2個控件的 layout_height="0dp", layout_weight="1",實現了豎直方向50%平均分割:

<LinearLayout 
  android:orientation="vertical">

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

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

</LinearLayout>

 

layout_weight 原來是可以這么用滴  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM