Search code examples
androidandroid-jetpack-composeandroid-jetpack-compose-layout

Text layout priority in Jetpack Compose


I have two texts in a row:

Row {
    Text(
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
        maxLines = 1,
        style = MaterialTheme.typography.h4,
        modifier = Modifier
            .background(Color.Cyan)
    )
    Spacer(
        modifier = Modifier
            .weight(1f)
            .requiredWidthIn(min = 10.dp)
    )
    Text(
        "Second",
        style = MaterialTheme.typography.h5,
        modifier = Modifier
            .requiredWidth(IntrinsicSize.Min)
            .background(Color.Yellow.copy(alpha = 0.5f))
    )
}

First one can be quite long. When it happens, second text gets compressed and disappears from the view.

requiredWidth(IntrinsicSize.Min) brings it back, but the first text is still taking all available width and goes under the second one.

enter image description here

When first text is small, I need second one be at the right, that's why I use spacer between them.

How can I add some layout priority to fix it?


Solution

  • You can add Arrangement.SpaceBetween in the Row and add the modifier weight(1f, fill= false) to the first Text:

    Row(horizontalArrangement = Arrangement.SpaceBetween,
        modifier = Modifier.fillMaxWidth()) {
        Text(
            "Lorem ....",
            maxLines = 1,
            style = MaterialTheme.typography.h4,
            modifier = Modifier
                .background(Color.Cyan)
                .weight(1f, fill= false)
        )
        Text(
            "Second",
            style = MaterialTheme.typography.h5,
            modifier = Modifier
                .background(Color.Yellow.copy(alpha = 0.5f))
        )
    }
    

    enter image description here enter image description here