關於weight屬性使用的一些細節

來源:互聯網
上載者:User

標籤:android   線性布局   weight   

之前被這個屬性困擾過好久,今天一個偶然的機會,終於把這個搞清楚了,現在與大家分享一下。

假設我們要在一個LinearLayout布局中顯示兩個按鈕,button1和button2,button2的寬度是button1的二倍,正常情況下使用weight應該是這樣的:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="horizontal" >    <Button        android:layout_width="0dp"        android:layout_height="wrap_content"        android:layout_weight="1"        android:text="button1" />    <Button        android:layout_width="0dp"        android:layout_height="wrap_content"        android:layout_weight="2"        android:text="button2" /></LinearLayout>

注意兩個button的寬都是0dp

:

可是如果換一種方式:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="horizontal" >    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_weight="1"        android:text="button1" />    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_weight="2"        android:text="button2" /></LinearLayout>

兩個button的寬度都是match_parent,情況立馬發生轉變:

我以前就在這裡不知道糾結了多少回,那麼我們到底該怎麼理解weight這個屬性呢?

設定了weight屬性的View的寬度等於原有寬度加上剩餘空間的佔比,其中剩餘空間是指螢幕寬度相對於控制項總寬度剩餘的空間大小。

以第一種情況為例

假設螢幕寬度為L,第一個button原有寬度是0dp,那麼該button的寬度為0+(L-0)×1/3 = (1/3)L;
其中(L-0)中,L表示螢幕寬度,0表示兩個控制項的總寬度

以第二種情況為例

假設螢幕寬度為L,因為兩個都是match_parent,所以總寬度是2L,那麼對於第一個button而言,它的寬度為:L+(L-2L)×1/3 = (2/3)L
其中(L-2L)中,L表示螢幕寬度,2L表示兩個控制項的總寬度

總結:建議大家在使用weight屬性的過程中把相應的寬或者高設定為0dp,這也是Google推薦的做法。水平排列的話寬設定為0dp,豎直排列的話高設定為0dp.

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。若有錯誤地方,還望批評指正,不勝感激。

關於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.