Offset an item taking its height into account in Jetpack Compose

Viewed 2613

I want to position my own component (say a Text component) vertically so that I can specify the y-offset relative to the bottom of the Text component. How could I do this in Jetpack compose?

So something like

Column {
    Text("Something", modifier = Modifier.offset(y=10.dp))
}

But instead of 10dp representing the top y-position of the Text component it would be the bottom y-position. Basically taking into account the height of the Text even if Text size changes. So y = offset.y - height

As I can see it, there's two problems:

  1. The font size can be changed, so I cannot hard code the text height.
  2. I need to know the size of my Text component during composition, but I don't know how to get that.
1 Answers

You could go for custom Composables,


@Composable
fun CustomText(y: Dp){
    Layout(content = { Text(text = "Lorem Ipsum") }){measurables, constraints ->
        val text = measurables[0].measure(constraints)
        layout(constraints.maxWidth, constraints.maxHeight){ //Change these per your needs
            text.placeRelative(IntOffset(0, y.value.roundToInt() - text.height))
        }
    }
}

You could also use a custom Modifier. Check out using the layout modifier

Related