I am new to compose and currently am facing problem when trying to create HorizontalPager
. Previously it was displayed so that pager item fills width and then height is same as width:
Surface(
modifier = Modifier
.fillMaxWidth()
.aspectRatio(1.0f),
elevation = 16.dp
) { ... }
Now I need to change it so that item still fills width but height wrap content and then every item's height is being evened out to heighest item. Also I would like minimum height be the same as width.
I found something like Intrinsic measurements but when tried to use it nothing happened:
Surface(
modifier = Modifier
.fillMaxWidth()
.height(IntrinsicSize.Min),
elevation = 16.dp
) { ... }
Also I have no idea how to set min height to be the same as width
I encountered this same problem. Unfortunately, there's no obvious standard practice in any of the Android Developer documentation.
First approach: IntrinsicSize
First, I tried with
IntrinsicSize.Min
, which did not work. I used the following code. But it won't even render in the Design panel. Instead it shows warnings/issues (java.lang.IllegalStateException: Asking for intrinsic measurements of SubcomposeLayout layouts is not supported
).Approach 2: onSizeChanged + MutableState
Inspired by some of the posts in Get height of element Jetpack Compose, I tried an approach where I stored the height of the largest element in the
HorizontalPager
as aMutableState
and used that to determine the minimum height of every element in theHorizontalPager
As can be seen in the demo above, the heights of all the elements stay the same. While this is the easiest (and only) working solution that I've found, I'm unfortunately unable to speak to whether it's the most performant/optimal approach. As discussed in some of the solutions in Get height of element Jetpack Compose, there may be a risk of unnecessary recompositions.