How can I align elements in a row, such that one e...
# compose
f
How can I align elements in a row, such that one element is centered and the other is attached to the right? The following solutions do not work:
Copy code
Row(horizontalArrangement = Arrangement.Center) {
            Text("Center")
            Text("Right", modifier = Modifier.fillMaxWidth().wrapContentWidth(Alignment.End))
        }
Copy code
Row(horizontalArrangement = Arrangement.Center) {
            Text("Center")
            Spacer(modifier = Modifier.weight(1f))
            Text("Right")
        }
As in both cases the
Center
element will get attached to the left. The desired behavior is in this image:
m
perhaps use the Compose implementation of
ConstraintLayout
f
I was hoping there was something simpler
m
I cannot rule out a way of doing this with
Row
, but your results are what I would expect from your code. In both cases, you are saying "I want the content to completely fill the row" via your whitespace rules. So, if the content fills the row,
"Center"
will be on the left (in LTR, anyway). The
Arrangement.Center
will be honored, more or less, but on the whole row content... and since that fills the row, it has no real effect.
f
yes I understand why those solutions don't work
It's possible to do with
Stack
, I don't know if this is a good solution
Copy code
Stack(Modifier.fillMaxWidth()) {
   Text("Center", modifier = Modifier.gravity(Alignment.Center))
   Text("Right", modifier = Modifier.gravity(Alignment.CenterEnd))
}
m
FWIW, the
ConstraintLayout
option would look like:
Copy code
ConstraintLayout(Modifier.fillMaxWidth()) {
    val (center, right) = createRefs()

    Text("Center", modifier = Modifier.constrainAs(center) {
      centerTo(parent)
    })
    Text("Right", modifier = Modifier.constrainAs(right) {
      end.linkTo(parent.end)
    })
  }
f
That is a lot simpler than I remembered, maybe I should do that instead, thank you
m
the DSL-based approach is fairly new
☝️ 2
a
Also if you'd still like to do it in a row, this'll get you there:
Copy code
Row {
    Spacer(Modifier.weight(1f))
    Text("Hello")
    Text("World", Modifier.weight(1f).wrapContentWidth(Alignment.End))
}
💡 1
two elements to the left and right with equal weight, which centers the middle element, then wrap the content width of the right element and align it to the end within the weighted space.
but please don't let that stop you from giving the new ConstraintLayout DSL a workout if you prefer 🙂
1
280 Views