Search code examples
androidkotlinandroid-layout

LayoutParams weight works unexpectedly


I'm trying to create LinearLayout with 2 children LinearLayouts. I can't use XML and should make this programmatically.

For parent I apply:

LayoutParams(MATCH_PARENT, WRAP_CONTENT, 1f)

1st child:

LayoutParams(MATCH_PARENT, WRAP_CONTENT, 0.3f)

2nd child:

LayoutParams(MATCH_PARENT, WRAP_CONTENT, 0.7f)

I expected child 2 to be bigger than child 1, but they're inverted. Child 1 takes more space than child 2.

Why I get this behaviour and how to fix it?


Solution

  • If you want a percentage based layout like that, the width of the children must be 0. Not MATCH_PARENT or WRAP_CONTENT (assuming a horizontal layout. If vertical, the same rule applies but for height). Weight is ignored if the width is non-zero