https://kotlinlang.org logo
f

Fudge

07/18/2020, 7:57 PM
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

Mark Murphy

07/18/2020, 8:03 PM
perhaps use the Compose implementation of
ConstraintLayout
f

Fudge

07/18/2020, 8:06 PM
I was hoping there was something simpler
m

Mark Murphy

07/18/2020, 8:11 PM
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

Fudge

07/18/2020, 8:16 PM
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

Mark Murphy

07/18/2020, 8:40 PM
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

Fudge

07/18/2020, 8:55 PM
That is a lot simpler than I remembered, maybe I should do that instead, thank you
m

Mark Murphy

07/18/2020, 8:55 PM
the DSL-based approach is fairly new
☝️ 2
a

Adam Powell

07/18/2020, 9:16 PM
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
12 Views