Search code examples
androidresizeandroid-linearlayout

How to resize the rows so that they always fill the full height of the parent?


I have a parent LinearLayout with a fixed size. At onCreate() I load data and add rows to the parent layout dynamically. Anywhere from 1-10 rows are loaded. I want the rows to always fill the parent, for example if I have 2 rows each row should have 50% height of the parent (50% + 50% = 100%). If I have 3 rows each row should use 33% of the parent height etc.

I tried to use an OnGlobalLayoutListener to get the height of the parent and resize the rows dynamically, unfortunately when I run the app the resizing is arbitrary at best. Sometimes the rows get resized, sometimes they get resized after a noticeable delay of about 0.5 seconds.

Is there a better way to achieve this? Maybe already in the XML as for example with layout_weight (given that the rows only get added in code)?


Solution

  • You can do this by setting the weight sum on the parent LinearLayout to the number of rows you have inside of it. If this is a vertical list of items you would then set the height of each row to 0 and set its weight to 1. If this is a horizontal list of items you do the same but set the width to 0 and set the weight to 1.