首先聲明只有在Linearlayout中,該屬性纔有效。之所以Android:layout_weight會引起爭議,是因爲在設置該屬性的同時,設置android:layout_width爲wrap_content和match_parent會造成兩種截然相反的效果。如下所示:
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:orientation="horizontal" >
- <TextView
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_weight="1"
- android:background="@android:color/black"
- android:text="111"
- android:textSize="20sp" />
- <TextView
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_weight="2"
- android:background="@android:color/holo_green_light"
- android:text="222"
- android:textSize="20sp" />
上面的佈局將兩個TextView的寬度均設爲match_parent,一個權重爲1,一個權重爲2.得到效果如下:
可以看到權重爲1的反而佔了三分之二!
再看如下佈局:
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:orientation="horizontal" >
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_weight="1"
- android:background="@android:color/black"
- android:text="111"
- android:textSize="20sp" />
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_weight="2"
- android:background="@android:color/holo_green_light"
- android:text="222"
- android:textSize="20sp" />
- </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