One Off the Slack: How Big Are We?
Eliezer Graber asked:
How would I find out the measurements for a specific node? For example, if I want to load an image from a remote service that accepts a width and height parameter, and I want to set that width and height to match the layout, how can I get that information?
The source of truth would be the space allocated in the layout, but my understanding of compose is that there’s a constraint system that makes it dynamic/responsive so I would have to wait for the actual layout to happen to get the pixel values
I was looking at something like accompanist but I need the size in order so that I can build the url with the width and height parameters.
A lightweight solution, from Google’s Adam Powell, is the
onSizeChanged()
modifier. However, specifically for image loading,
Google’s Ian Lake recommended the requestBuilder
option in Accompanist,
the library family from Google’s Chris Banes:
That’s exactly what accompanist provides in its
requestBuilder
(for Coil in this instance) - the ability to change thedata
(i.e., the URI) based on the size you’re passed
It uses onSizeChanged under the hood so it is good to know about that as a tool in your toolbox, but image loading isn’t something that every dev should have to write from scratch 😛
Google’s Jim Sproch also pointed out BoxWithConstraints
:
BoxWithConstraints
is super useful whenever you’re building any sort of responsive layout, because it allows you to look at the space available before deciding what widgets you want to render, what orientation you want to render them, how much padding you want around each widget, etc.
Adam felt that was overkill:
Modifier.onSizeChanged {}
will be considerably less overhead thanBoxWithConstraints
if all you need is the measured size of the element.BoxWithConstraints
is good if you would change the actual structure of the content based on the incoming layout constraints.
So, to sum up:
-
If you just want to customize the source of an image based on the available space, look for options in your image-loading library, like Accompanist
-
If that is not available, and all you need is the size of the element once it is determined, try the
onSizeChanged()
modifier -
If you want structural changes based on size, consider
BoxWithConstraints
Read the original thread in the kotlinlang Slack workspace. Not a member? Join that Slack workspace here!