Android布局中的layout_weight和weightSum屬性的詳解及使用


由於Android設備的尺寸大小不一,種類繁多,當我們在開發應用的時候就要考慮屏幕的適配型了,盡可能讓我們的應用適用於主流機型的尺寸,這樣我們的應用不會因為尺寸不同而不美觀,解決屏幕適配問題的方法有很多,在這里我所講的是其中的一種解決方案---巧妙的使用layout_weight屬性。

     在布局中Layout_weight屬性的作用:它是用來分配屬於空間的一個屬性,你可以設置它所占據屏幕的權重。

1.layout_weight屬性  

   首先我們先看下效果,然后再給出計算公式。

 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   
 7     <Button  
 8         android:layout_width="0dp"  
 9         android:layout_height="wrap_content"  
10         android:layout_weight="1"  
11         android:text="buttton1" />  
12   
13     <Button  
14         android:layout_width="0dp"  
15         android:layout_height="wrap_content"  
16         android:layout_weight="2"  
17         android:text="button2" />  
18   
19 </LinearLayout>

 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   
 7     <Button  
 8         android:layout_width="match_parent"  
 9         android:layout_height="wrap_content"  
10         android:layout_weight="1"  
11         android:text="buttton1" />  
12   
13     <Button  
14         android:layout_width="match_parent"  
15         android:layout_height="wrap_content"  
16         android:layout_weight="2"  
17         android:text="button2" />  
18   
19 </LinearLayout> 

效果如下:

 

 

    計算公式如下:

     首先我們假設屏幕的寬度為L

     實際寬度 = 控件原來的長度 + 剩余空間所占百分比的寬度

     比如第一圖片上的計算式子如下

      button1實際寬度 = 0 + 1/(1+2)L= 1/3L     button2實際寬度 = 0 +2/(1+2)L = 2/3L

     第二張圖片上的計算式子如下 

      button1實際寬度 = L +1[L-(L+L)]/(1+2) L = 2/3 L    button2實際寬度 = L + 2[L-(L+L)]/(1+2) L = 1/3 L

     好了,看到這里weight屬性是不是很好理解,最主要的是對剩余空間的理解 。

2.weightSum屬性

android:weightSum屬性在官方文檔中的解釋包含下面的內容:“定義weight綜合的最大值,如果未指定該值,以所有子師徒的layout_weight屬性的累加值作為總和的最大值。典型案例是:通過指定子視圖的layout_weight屬性為0.5.並設置LinearLayout的weightSum屬性為1.0,實現子視圖占據可用寬高的50%”。

 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
 2     android:layout_width="match_parent"  
 3     android:layout_height="wrap_content"  
 4     android:gravity="center"  
 5     android:orientation="horizontal"  
 6     android:weightSum="1" >  
 7   
 8     <Button  
 9         android:layout_width="0dp"  
10         android:layout_height="wrap_content"  
11         android:layout_weight="0.5"  
12         android:text="test" />  
13   
14 </LinearLayout>  

 


免責聲明!

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



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