【发布时间】:2023-01-05 01:59:54
【问题描述】:
有一段时间我都在为这个问题发愁,无论我看了多少教程和读了多少代码 sn-ps,我都无法理解这个概念。
我只是想将标记图像放在我点击它的另一个图像之上。
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyLayout() {
PlaceMarkerOnImage(it)
}
}
}
@Composable
private fun MyLayout(
placeMarker: (Offset) -> Unit
) {
val painter: Painter = painterResource(id = R.drawable.image)
Column(Modifier.fillMaxSize()) {
Box(
modifier = Modifier.weight(0.95f)
) {
Image(
contentScale = FillBounds,
painter = painter,
contentDescription = "",
modifier = Modifier.pointerInput(Unit) {
detectTapGestures(
onTap = {
placeMarker(it)
}
)
}
)
}
Button(
onClick = { },
modifier = Modifier.weight(0.05f),
shape = MaterialTheme.shapes.small
) {
Text(text = "Edit Mode")
}
}
}
@Composable
private fun PlaceMarkerOnImage(offset: Offset) {
Image(
painter = painterResource(id = R.drawable.marker),
contentScale = ContentScale.Crop,
contentDescription = "",
modifier = Modifier.offset(offset.x.dp, offset.y.dp)
)
}
}
但这是错误的,因为我在调用 PlaceMarkerOnImage 时遇到了可怕的编译错误:@Composable 调用只能在@Composable 函数的上下文中发生
我不明白..我得到的是被覆盖的onCreate函数不是@Composable,因此不能从它调用@Composable函数,我也不能只向它添加@Composable注释。
但是我从 setContent 块中调用了两个可组合函数。调用MyLayout()没问题,为什么调用PlaceMarkerOnImage(Offset)有问题?
【问题讨论】:
标签: android kotlin android-jetpack-compose composable