Matter Cat
Matter Cat

Reputation: 1578

Does programmatically setting layout sizes actually save on performance?

So whenever I try to use layout_weights within each other to achieve the layouts I want, Android Studio helpfully tells me that nested weights are bad for performance. Various answers here on SO say that it's okay to nest them for a couple layers of deep, but don't overdo it. I'm not sure how deep is too deep, o what I'm trying instead is doing something like this:

    //get pix size of device screen
    int[] dimens = ImageUtils.getScreenDimensions(getWindowManager());

    //programmatically set height of my two sections to the percentages that I want
    upper.getLayoutParams().height = (int) (dimens[1]*0.8);
    lower.getLayoutParams().height = (int) (dimens[1]*0.2);

    // do the same thing for the left and right sections of our upper block
    upperLeft.getLayoutParams().width = (int) (dimens[0] * 0.5);
    upperRight.getLayoutParams().width = (int) (dimens[0] * 0.3);

...so on and so forth

And I mean, it works. I get some nice percentage-based layouts. My question is though, does that actually help with performance at all? Or am I just doing the same thing in a more complicated and fancy fashion?

Edit: adding desired layout. I guess I could use a grid layout if necessary? Or would just plain old percentages work?

Layout that I want

Upvotes: 2

Views: 102

Answers (2)

Jim
Jim

Reputation: 10288

"Nested Layouts" implies that Android does not know how big each layout should be without iterating over each layout setting to determine if the size should be changed based on other layouts.

This means that "nesting" could result in many iterations of trying to size each layout, then trying to figure out if child layouts change based on changes to parent layouts and sibling layouts.

If you can determine the size of a layout programmatically (which it seems you can do), then the LayoutManager will use the sizes that you dictate and not try to layout the screen and then check to see whether the layouts have been sized properly.

That said, it might not really matter if you only have a dozen or so layouts. The performance hit happens when several dozens of layouts (or more) need to be measured. That is why a lot of comments on SO say that it doesn't really matter - most times, a few dozen layouts are all that are present on the screen. (HINT: if you have a ListView or GridView or something that requires an indeterminate number of layouts be used; then nesting matters and recycling views matter)

Upvotes: 1

David Ou
David Ou

Reputation: 1

If these layout weights aren't going to change dynamically, you are better off defining them in the XML layouts. Not only will your intention be clearer, but Android does perform optimizations when inflating your layouts.

Upvotes: 0

Related Questions