android:layout_weight的真實含義

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

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

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


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

再看如下佈局:

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

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


左邊 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就可以理解爲佔比了!



轉自:http://blog.csdn.net/yanzi1225627/article/details/24667299

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章