What does android:layout_weight mean?

前端 未结 13 1287
遇见更好的自我
遇见更好的自我 2020-11-21 06:14

I don\'t understand how to use this attribute. Can anyone tell me more about it?

13条回答
  •  我寻月下人不归
    2020-11-21 07:00

    In a nutshell, layout_weight specifies how much of the extra space in the layout to be allocated to the View.

    LinearLayout supports assigning a weight to individual children. This attribute assigns an "importance" value to a view, and allows it to expand to fill any remaining space in the parent view. Views' default weight is zero.

    Calculation to assign any remaining space between child

    In general, the formula is:

    space assigned to child = (child's individual weight) / (sum of weight of every child in Linear Layout)

    Example 1

    If there are three text boxes and two of them declare a weight of 1, while the third one is given no weight (0), then remaining space is assigned as follows:

    1st text box = 1/(1+1+0)

    2nd text box = 1/(1+1+0)

    3rd text box = 0/(1+1+0)

    Example 2

    Let's say we have a text label and two text edit elements in a horizontal row. The label has no layout_weight specified, so it takes up the minimum space required to render. If the layout_weight of each of the two text edit elements is set to 1, the remaining width in the parent layout will be split equally between them (because we claim they are equally important).

    Calculation:

    1st label = 0/(0+1+1)

    2nd text box = 1/(0+1+1)

    3rd text box = 1/(0+1+1)

    If, instead, the first one text box has a layout_weight of 1, and the second text box has a layout_weight of 2, then one third of the remaining space will be given to the first, and two thirds to the second (because we claim the second one is more important).

    Calculation:

    1st label = 0/(0+1+2)

    2nd text box = 1/(0+1+2)

    3rd text box = 2/(0+1+2)


    Source article

提交回复
热议问题