What does android:layout_weight mean?

前端 未结 13 1240
遇见更好的自我
遇见更好的自我 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:04

    If there are multiple views spanning a LinearLayout, then layout_weight gives them each a proportional size. A view with a bigger layout_weight value "weighs" more, so it gets a bigger space.

    Here is an image to make things more clear.

    Theory

    The term layout weight is related to the concept of weighted average in math. It is like in a college class where homework is worth 30%, attendance is worth 10%, the midterm is worth 20%, and the final is worth 40%. Your scores for those parts, when weighted together, give you your total grade.

    enter image description here

    It is the same for layout weight. The Views in a horizontal LinearLayout can each take up a certain percentage of the total width. (Or a percentage of the height for a vertical LinearLayout.)

    The Layout

    The LinearLayout that you use will look something like this:

    
    
        
    
    
    

    Note that you must use layout_width="match_parent" for the LinearLayout. If you use wrap_content, then it won't work. Also note that layout_weight does not work for the views in RelativeLayouts (see here and here for SO answers dealing with this issue).

    The Views

    Each view in a horizontal LinearLayout looks something like this:

    Note that you need to use layout_width="0dp" together with layout_weight="1". Forgetting this causes many new users problems. (See this article for different results you can get by not setting the width to 0.) If your views are in a vertical LinearLayout then you would use layout_height="0dp", of course.

    In the Button example above I set the weight to 1, but you can use any number. It is only the total that matters. You can see in the three rows of buttons in the first image that I posted, the numbers are all different, but since the proportions are the same, the weighted widths don't change in each row. Some people like to use decimal numbers that have a sum of 1 so that in a complex layout it is clear what the weight of each part is.

    One final note. If you have lots of nested layouts that use layout_weight, it can be bad for performance.

    Extra

    Here is the xml layout for the top image:

    
    
    
        
    
        
    
            

提交回复
热议问题