How does android:layout_weight work?

前端 未结 8 2046
后悔当初
后悔当初 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:52

    I know this is late but hopefully it helps people:

    Use android:weightSum on the parent. Here is a link to the dev docs.

    http://developer.android.com/reference/android/widget/LinearLayout.html#attr_android:weightSum

    Use android:weightSum of 1.0 on the parent and then use 0.x on the child views with android:layout_weight in order for them to use that ratio of space.

    0 讨论(0)
  • 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)

    0 讨论(0)
  • 2020-12-02 21:01

    If you are using fill_parent in a LinearLayout the layout will take as much space as possible and all layout items defined later will have to deal with the space left.

    If you set the height of both of you LinearLayouts to wrap_content the weight should work as documented.

    0 讨论(0)
  • 2020-12-02 21:02

    I had the same problem. The trick is not to use "wrap_content" or "fill_parent" for the controls you are setting a weight to. Instead set the layout_height to 0px (when inside a vertical layout) and then the child controls will get proportioned per the weight values.

    0 讨论(0)
  • 2020-12-02 21:03

    If you get the error as

    error

    Suspicious size: this will make the view invisible, probably intended for layout ...

    remember to set the correct parameter on android:orientation in parent

    0 讨论(0)
  • 2020-12-02 21:07

    If the orientation of linearlayout is vertical,then set layout_height as 0dp. In case of horizontal layout set layout_width as 0dp.

    If we do not follow above rules,the view tends to take up space as per specified attributes and hence the alignment is not as per expectation.

    0 讨论(0)
提交回复
热议问题