How to custom left/right align items in android jetpack compose Row
N

2

44

I want a Row in Jetpack Compose, something like this:

----------------------------------------------------
| A |   B   |                                  | C |
----------------------------------------------------

I want A & B to be left aligned, next to each other and C at the end. I don't know if the existing horizontal arrangement has ways to do this. Also I think, nesting Rows may not be a good idea. What's the best way to achieve this?

Nichellenichol answered 2/4, 2022 at 6:23 Comment(0)
A
101

You can use Spacer with Modifier.weight:

Row {
    Text("a")
    Text("b")
    Spacer(Modifier.weight(1f))
    Text("c")
}

In more complex scenario, when your first text is multiline, you can apply Modifier.weight to this item itself - and making sure content inside is aligned as you expect, e.g. Start in this case by default:

Row {
    Text(
        "some\nmultiline\ntext",
        modifier = Modifier
            .weight(1f)
    )
    Text("c")
}
Angelikaangelina answered 2/4, 2022 at 7:19 Comment(1)
it will not work for long text in the case of the first textTranscurrent
C
4

The accepted answer will not work if the first Text is too long. In that case, the third text will not be shown.

This should work:

                Row {
                    Text("a")
                    Text(
                        modifier = Modifier.weight(1f),
                        text = "b"
                    )
                    Text("c")
                }
Conversationalist answered 3/5, 2023 at 17:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.