【问题标题】:Offset an item taking its height into account in Jetpack Compose在 Jetpack Compose 中考虑项目的高度来偏移项目
【发布时间】:2021-10-21 21:39:11
【问题描述】:

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

类似

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

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

在我看来,有两个问题:

  1. 字体大小可以改变,所以我不能硬编码文本高度。
  2. 在合成过程中我需要知道我的 Text 组件的大小,但我不知道如何获得。

【问题讨论】:

  • 其实如果是从底部开始测量偏移量,那么不应该是y = offset.y -height吗?
  • 没错,谢谢! :) 我会修复

标签: android android-jetpack-compose


【解决方案1】:

您可以选择自定义 Composable,


@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))
        }
    }
}

您也可以使用自定义修饰符。查看using the layout modifier

【讨论】:

  • 谢谢!这实际上似乎适合我想做的事情。能够相对于父项准确定位项目,并提供测量项目的可能性。
猜你喜欢
  • 2022-07-26
  • 1970-01-01
  • 1970-01-01
  • 2021-11-30
  • 1970-01-01
  • 2022-11-08
  • 1970-01-01
  • 1970-01-01
  • 2022-10-04
相关资源
最近更新 更多