Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically adjust the weighting of columns in a row based on string length

I have a layout with two texts, one on left side and one on right side. If both texts are long, left one should occupy 60%, and right one 40% of the width. But if right text is shorter than 40%, the left one should take all the available space.

Here are the examples: long right part and: enter image description here So I would like to write something like this:

Row {
    Text(text = left, modifier = modifier.padding(8.dp).weight(<min 0.6f>))
    Text(text = right, modifier = modifier.padding(8.dp).weight(<max 0.4f>))
}

Is there any way to achieve this?

like image 683
netimen Avatar asked Sep 20 '25 23:09

netimen


1 Answers

Finally, I figured it out. Here is the modifier:

fun Modifier.maxWidth(
    fraction: Float = 1f,
) = layout { measurable, constraints ->
    val maxWidth = (constraints.maxWidth * fraction).roundToInt()
    val width = measurable.maxIntrinsicWidth(constraints.maxHeight).coerceAtMost(maxWidth)

    val placeable = measurable.measure(Constraints(constraints.minWidth, width, constraints.minHeight, constraints.maxHeight))
    layout(width, placeable.height) {
        placeable.placeRelative(0, 0)
    }
}

So we can use it like this:

Row {
    Text(text = left, modifier = modifier.padding(8.dp).weight(1f)) // left text uses all the available space
    Text(text = right, modifier = modifier.padding(8.dp).maxWidth(fraction = 0.4f)) // right text can be 40% of the parent or less
}
like image 185
netimen Avatar answered Sep 23 '25 07:09

netimen