Eyjafl
Eyjafl

Reputation: 2215

Make the first element in a Row wrap without occupying all available space

In Android Compose I want to create a Row which occupies all available width and contains two texts:

How this should look

  1. The first text should be at the start of the row.
  2. The second text should be right after the first one.
  3. The first text is of variable size, may soft-wrap, and should overflow first.
  4. The second text is fixed, occupies one line max, and should overflow only if the first one cannot shrink any further.

I tried my best to do this, but I can only achieve either of these things:

a. Make the second text go right after the first one but overflow first (by simply placing them one after another in the code).

Row(
    modifier = Modifier.fillMaxWidth(),
    verticalAlignment = Alignment.CenterVertically
) {
    Text(text = title)

    Text(
        text = "Fixed text",
        maxLines = 1
    )
}

My Attempt a

b. Make the first text overflow first, but occupy the whole available space when it doesn't overflow (by adding Modifier.weight(1f) to the first text).

Row(
    modifier = Modifier.fillMaxWidth(),
    verticalAlignment = Alignment.CenterVertically
) {
    Text(
        text = title,
        modifier = Modifier.weight(1f)
    )

    Text(
        text = "Fixed text",
        maxLines = 1
    )
}

My attempt b

How can I achieve the described behavior? I know I can probably use ConstraintLayout but I would like to avoid it if possible.

Upvotes: 6

Views: 1132

Answers (1)

Thales Isidoro
Thales Isidoro

Reputation: 3179

You can use the fill parameter of the weight, by default it set to true, therefore automatically occupies all available space. But if you switch to false you will get what you want.

Example:

// PreviewShortTextWithNoFill
Row(
    modifier = Modifier
        .fillMaxWidth()
        .padding(all = 16.dp),
    horizontalArrangement = Arrangement.spacedBy(space = 8.dp),
    verticalAlignment = Alignment.CenterVertically
) {
    Text(
        modifier = Modifier.weight(weight = 1F, fill = false),
        text = "random short text"
    )

    Text(
        text = "fixed text",
        maxLines = 1
    )
}

PreviewShortTextWithNoFill

Upvotes: 12

Related Questions