LinearLayout 中,有時後會用到 weight 來讓版面達到滿版的效果。但是有時候 child view 的 weight 越大,暫的空間越大,有時候又是相反。為了釐清只好找了 LinearLayout 的 Source 來研究:(widget/LinearLayout.java)
1147 // Either expand children with weight to take up available space or 1148 // shrink them if they extend beyond our current bounds 1149 int delta = widthSize - mTotalLength; 1150 if (delta != 0 && totalWeight > 0.0f) { 1151 float weightSum = mWeightSum > 0.0f ? mWeightSum : totalWeight; ... ... 1169 float childExtra = lp.weight; 1170 if (childExtra > 0) { 1171 // Child said it could absorb extra space -- give him his share 1172 int share = (int) (childExtra * delta / weightSum); 1173 weightSum -= childExtra; 1174 delta -= share;上面這兩段基本上就是原因,當所有 child view 算出來的高度/寬度小於自己的高/寬的時候,delta 是正的,會依照 weight 的比例分給這些 child view 讓 weight > 0 的 child view 來吸收多出來的空間。反之,若寬度超過預算,也是由這些 child view 縮小吸收,所以會才會有兩種不同的狀況。
沒有留言:
張貼留言