Issue
Is there a way in Compose to align a composable next to a centered item without using ConstraintLayout
?
I could use a Spacer
and Weights
like this
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically,
) {
Spacer(Modifier.weight(1f))
Button(...)
Label(Modifier.weight(1f),...)
}
Problem is that I display the Label
conditionally and if I hide the two elements with the weights, the button moves slightly.
Also not sure if using weights is producing more performance impact than the ConstraintLayout
in the first place.
Solution
The Modifier.weight
is the right way to create such a layout. I'm not sure if the performance is better than ConstraintLayout
, but certainly not worse.
If you run into performance problems, you should create a problem on the google issue tracker, since that's how Compose is supposed to be used. Personally, I haven't encountered any performance problems related to weight
, but the technology is fairly recent, so you can't completely rule out such a possibility.
In your case, you need to have some representation at any given time, to which you can apply Modifier.weight
. You can use if
-else
and add Spacer
in else
case, but I prefer to use Box
with optional content: it looks cleaner and will work correctly in case you add animation.
Default Box
contentAlignment
is Alignment.TopStart
, which will work exactly as needed in your case, but in some other cases, you can override it or add more Spacers
inside.
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically,
) {
Spacer(Modifier.weight(1f))
Button(...)
Box(Modifier.weight(1f)) {
if (condition) {
Label(...)
}
}
}
Answered By - Phil Dukhov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.