在 Jetpack Compose 中考虑项目的高度来偏移项目

Joh*_*aul 10 android android-jetpack-compose

我想垂直放置我自己的组件(例如文本组件),以便可以指定相对于文本组件底部的 y 偏移。我怎样才能在 Jetpack compose 中做到这一点?

所以像

Column {
    Text("Something", modifier = Modifier.offset(y=10.dp))
}
Run Code Online (Sandbox Code Playgroud)

但 10dp 不是代表文本组件的顶部 y 位置,而是底部 y 位置。即使文本大小发生变化,基本上也会考虑文本的高度。所以y = offset.y - height

据我所知,有两个问题:

  1. 字体大小可以更改,因此我无法对文本高度进行硬编码。
  2. 我需要知道合成过程中文本组件的大小,但我不知道如何获取它。

Ric*_*per 5

您可以选择自定义可组合项,


@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))
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您还可以使用自定义修饰符。使用修改器检查layout