简体   繁体   中英

How layout_weight works?

I researched on another stackoverflow question//answer and found a working definition of layout_weight to be that "This attribute assigns an "importance" value to a view, and allows it to expand to fill any remaining space in the parent view" (source: What does android:layout_weight mean? )

I am trying to apply that concept to my code. Currently my code (without the layout weights) is

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >
    <TextView 
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="Home"
       android:gravity="center"
     />
    <TextView
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="About"
       android:gravity="center"
      />
</LinearLayout>

And the current layout is http://imgur.com/eq6q0I8 (the home should take up all the space bc of match_parent)

However if i add android:layout_weight="1" to both text views, i get this layout http://imgur.com/fscM0Zr

(Both are visible and share same amount of space)

My question is how is this happening from that working definition of layout_weight? layout_weight in this example will assign extra space equally to both the text views. But there is no extra space because the first one has width match_parent which will make it take the width of the entire parent(no extra space)

How is this happening ?

To fix the ideas, let's say that LinearLayout's width is 100px.

  • TextView Home is MATCH_PARENT so 100px
  • TextView About is MATCH_PARENT so 100px

So, total width used by children is 100px+100px = 200px

Now, let's compute the remaining width : this is the difference between the available width and the width used by all children :

RemainingWidth = AvailableWidth (100px) - TotalWidthUsedByChildren (200px) = -100px

Note that it is negative

There is 2 child views, so distribute the remaining width to each of them according their weight. In this case each child receive 50% of the remaining... it means that each child receive -50px.

So finally :

  • TextView Home width is 100px + -50px = 50px
  • TextView About width is 100px + -50px = 50px

Perfectly logic, but not very intuitive. So the recommendation when using layout_weight is to always set the width of chid views to 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM