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

來源:互聯網
上載者:User

在Android的控制項布局中,有一個奇葩的 layout_weight 屬性,定義如下:

layout_weight : 用於指定剩餘空閑空間的分割比例。用法:

01 <LinearLayout
02   android:orientation="horizontal">
03  
04   <TextView
05       android:layout_width="wrap_content"
06       android:layout_height="wrap_height"
07       android:layout_weight="1"
08       android:text="888"/>
09  
10   <TextView
11       android:layout_width="wrap_content"
12       android:layout_height="wrap_height"
13       android:layout_weight="1"
14       android:text="999999"/>
15  
16 </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%平均分割:

01 <LinearLayout
02   android:orientation="horizontal">
03  
04   <TextView
05       android:layout_width="0dp"
06       android:layout_height="wrap_height"
07       android:layout_weight="1"
08       android:text="888"/>
09  
10   <TextView
11       android:layout_width="0dp"
12       android:layout_height="wrap_height"
13       android:layout_weight="1"
14       android:text="999999"/>
15  
16 </LinearLayout>

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

01 <LinearLayout
02   android:orientation="vertical">
03  
04   <TextView
05       android:layout_width="wrap_content"
06       android:layout_height="0dp"
07       android:layout_weight="1"
08       android:text="888"/>
09  
10   <TextView
11       android:layout_width="wrap_content"
12       android:layout_height="0dp"
13       android:layout_weight="1"
14       android:text="999999"/>
15  
16 </LinearLayout>

layout_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.