android:layout_weight屬性的工作原理

來源:互聯網
上載者:User

標籤:

    android:layout_weight屬性告知LinearLayout如何進行子組件的布置安排。

我們已經為兩個組件設定了同樣的值,但這並不意味它們在螢幕上佔據著同樣的寬

度。在決定子組件視圖的寬度時,LinearLayout使用的是layout_width與

layout_weight參數的混合值。LinearLayout是分兩個步驟來設定視圖寬度的。

 

activity_main.xml

 

1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2     xmlns:tools="http://schemas.android.com/tools" 3     android:layout_width="match_parent" 4     android:layout_height="match_parent" 5     android:orientation="horizontal" 6     tools:context=".MainActivity" > 7  8     <CheckBox 9         android:id="@+id/checkBox1"10         android:layout_width="wrap_content"11         android:layout_height="wrap_content"12         android:layout_weight="1"13         android:text="顯示" />14 15     <Button16         android:id="@+id/button1"17         android:layout_width="wrap_content"18         android:layout_height="wrap_content"19         android:layout_weight="1"20         android:text="按鈕" />21 22 </LinearLayout>
View Code

 

 

 

    第一步,LinearLayout查看layout_width屬性值(豎直方位則查看layout_height

屬性值)。Button和CheckBox組件的layout_width屬性值都設定為wrap_content,因此

它們獲得的空間大小僅夠繪製自身,1所示

 

    圖1 第一步:基於layout_width屬性值分配的空間大小

    圖2 第二步:基於1∶1layout_weight屬性值分配的額外空間

     在布局中,Button和CheckBox組件擁有相同的layout_weight屬性值,因

此它們均分了同樣大小的額外空間。如將Button組件的weight值設定為2,那麼

它將獲得2/3的額外空間,CheckBox組件則獲得剩餘的1/3,3所示。


    圖3基於2∶1layout_weight屬性值不等比分配的額外空間

  weight設定值也可以是浮點數。對於weight設定值,開發人員有著各自的使用習慣。

在activity_main.xml中,我們使用的是一種cocktail recipe式的weight設定風格

。另一種常見的設定方式是各組件屬性值加起來等於1.0或100。這樣,上個例子中按鈕

組件的weight值則應該是0.66或66。
  如想讓LinearLayout分配完全相同的寬度給各自的視圖,該如何處理呢?很簡單,

只需設定各組件的layout_width屬性值為0dp以避開第一步的空間分配就可以了,這樣

LinearLayout就會只考慮使用layout_weight屬性值來完成所需的空間分配了,4

所示。

    圖4layout_width="0dp",基於1∶1layout_weight屬性值

 

android: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.