kotlin 尝试在jetpack compose中切换图像时出错

a8jjtwal  于 12个月前  发布在  Kotlin
关注(0)|答案(2)|浏览(112)

我创建了一个函数,并希望将条件后的激活传递给另一个函数,但它给了我这个错误:@Composable invocations can only happen from the context of a @Composable function
下面是我的代码:

@Composable
fun RotatingImage() {
    val rotationState = rememberInfiniteTransition()
    val rotation by rotationState.animateFloat(
        initialValue = 0f,
        targetValue = 360f,
        animationSpec = infiniteRepeatable(
            animation = keyframes {
                durationMillis = 3000 },
            repeatMode = RepeatMode.Restart
        ), label = ""
    )

    val image: Painter = painterResource(id = R.drawable.andew) // Замените на свой ресурс

    Image(
        painter = image,
        contentDescription = null, // Может быть null, если не нужно описание
        modifier = Modifier
            .size(100.dp) // Задайте размер изображения
            .rotate(rotation) // Примените вращение
    )
}

@Composable
fun Clickc() {
    var count = remember { mutableStateOf(0) }
    Column {
        Text(text = count.value.toString(), color = Color.White)
        Image(
            painter = painterResource(id = R.drawable.watermelon),
            contentDescription = "im2",
            modifier = Modifier.clickable(onClick = {
                when (++count.value) {
                    10 -> RotatingImage() // <-- THERE'S THE PROBLEM
                }
            })
        )
    }
}

字符串

ohtdti5x

ohtdti5x1#

您尝试从onClick回调中调用RotatingImage(),但该回调不在@Composable范围内。
你需要像这样把它分开:

Column {
    Text(text = count.value.toString(), color = Color.White)
    if (count < 10) {
        Image(
            painter = painterResource(id = R.drawable.watermelon),
            contentDescription = "im2",
            modifier = Modifier.clickable(onClick = { ++count.value })
        )
    } else {
        RotatingImage()
    }
}

字符串

6jjcrrmo

6jjcrrmo2#

不要忘记一个Composable函数必须快速执行。如果你试图在回调函数中定义一个Composable函数,那么它的状态必须被维护,这样系统就知道它是否应该被绘制。
系统无法解释这一点,因此,不是在onClick方法中调用可组合对象,而是在那里保存状态。

@Composable
fun Clickc() {
    var count = remember { mutableStateOf(0) }
    val (showRotateImage, setShowRotateImage) = remember { mutableStateOf(false) }
    Column {
        Text(text = count.value.toString(), color = Color.White)
        Image(
            painter = painterResource(id = R.drawable.watermelon),
            contentDescription = "im2",
            modifier = Modifier.clickable(onClick = {
                if (++count.value == 10) {
                    setShowRotateImage(true)
                }
            })
        )
        if(showRotateImage){
            RotatingImage()
        }
    }
}

字符串

相关问题