天天看點

android:layout_weight的含義

感謝原作者,原帖位址:http://blog.csdn.net/yanzi1225627/article/details/24667299

首先聲明隻有在Linearlayout中,該屬性才有效。之是以android:layout_weight會引起争議,是因為在設定該屬性的同時,設定android:layout_width為wrap_content和match_parent會造成兩種截然相反的效果。如下所示:

[html] view plain copy print ?

android:layout_weight的含義
android:layout_weight的含義
  1. <LinearLayout  
  2.        android:layout_width="match_parent"  
  3.        android:layout_height="wrap_content"  
  4.        android:orientation="horizontal" >  
  5.        <TextView  
  6.            android:layout_width="match_parent"  
  7.            android:layout_height="wrap_content"  
  8.            android:layout_weight="1"  
  9.            android:background="@android:color/black"  
  10.            android:text="111"  
  11.            android:textSize="20sp" />  
  12.        <TextView  
  13.            android:layout_width="match_parent"  
  14.            android:layout_height="wrap_content"  
  15.            android:layout_weight="2"  
  16.            android:background="@android:color/holo_green_light"  
  17.            android:text="222"  
  18.            android:textSize="20sp" />  

上面的布局将兩個TextView的寬度均設為match_parent,一個權重為1,一個權重為2.得到效果如下:

android:layout_weight的含義

可以看到權重為1的反而占了三分之二!

再看如下布局:

[html] view plain copy print ?

android:layout_weight的含義
android:layout_weight的含義
  1. <LinearLayout  
  2.     android:layout_width="match_parent"  
  3.     android:layout_height="wrap_content"  
  4.     android:orientation="horizontal" >  
  5.     <TextView  
  6.         android:layout_width="wrap_content"  
  7.         android:layout_height="wrap_content"  
  8.         android:layout_weight="1"  
  9.         android:background="@android:color/black"  
  10.         android:text="111"  
  11.         android:textSize="20sp" />  
  12.     <TextView  
  13.         android:layout_width="wrap_content"  
  14.         android:layout_height="wrap_content"  
  15.         android:layout_weight="2"  
  16.         android:background="@android:color/holo_green_light"  
  17.         android:text="222"  
  18.         android:textSize="20sp" />  
  19. </LinearLayout>  

即寬度為wrap_content,得到視圖如下:

android:layout_weight的含義

左邊 TextView占比三分之一,又正常了。

android:layout_weight的真實含義是:一旦View設定了該屬性(假設有效的情況下),那麼該 View的寬度等于原有寬度(android:layout_width)加上剩餘空間的占比!

設螢幕寬度為L,在兩個view的寬度都為match_parent的情況下,原有寬度為L,兩個的View的寬度都為L,那麼剩餘寬度為L-(L+L) = -L, 左邊的View占比三分之一,是以總寬度是L+(-L)*1/3 = (2/3)L.事實上預設的View的weight這個值為0,一旦設定了這個值,那麼所在view在繪制的時候執行onMeasure兩次的原因就在這。

Google官方推薦,當使用weight屬性時,将width設為0dip即可,效果跟設成wrap_content是一樣的。這樣weight就可以了解為占比了!