How does android:layout_weight work?

前端 未结 8 2096
后悔当初
后悔当初 2020-12-02 20:35

When I have the following, it shows top layout with four colors has much smaller area than the bottom layout area.

According to this documentation, when you add more

8条回答
  •  情书的邮戳
    2020-12-02 20:55

    The solution is to set layout_height to 0px when you use layout_weight.

    But why do you observe this apparently strange/inversed behavior ?

    Shortly : the remaining space is negative and so the child with weight 4 receive more negative space and it's height is more reduced.

    Details :

    Assume that the height of your parent vertical layout is 100 pixels.

    Layout height on each child is fill_parent (i.e. each child is also 100 pixels height)

    The total height of all child = 2*100 pixels

    The remaining height = 100 - (2*100) = -100 pixels (it is negative)

    Now, let's distribute this remaining height between child. The first one will receive the biggest part : 80% (i.e. -100*4/(4+1)). The second child receive 20% (i.e. -100*1/(4+1))

    Now compute the resulting height :

    child 1 : 100 + (-80) = 20px

    child 2 : 100 + (-20) = 80px

    Nothing strange here, only mathematics. Just be aware that remaining space can be negative ! (or set the height explicitly at 0 as it is recommended)

提交回复
热议问题