gpt4 book ai didi

android - @composable 调用只能在 @composable 函数的上下文中发生

转载 作者:行者123 更新时间:2023-12-02 13:16:22 43 4
gpt4 key购买 nike

单击工具栏操作时,我试图显示 toast 消息,但出现此错误

@composable invocations can only happen from the context of an@composable function


代码:
@Composable
fun Toolbar() {
TopAppBar(title = { Text(text = "Jetpack Compose") }, navigationIcon = {
IconButton(onClick = {}) {
Icon(Icons.Filled.Menu)
}
}, actions = {
IconButton(onClick = {
showMessage(message = "test")
}) {
Icon(vectorResource(id = R.drawable.ic_baseline_save_24))
}
})
}

@Preview
@Composable
fun ToolbarPreview(){
Toolbar()
}

@Composable
fun showMessage(message:String){
Toast.makeText(ContextAmbient.current, message, Toast.LENGTH_SHORT).show()
}

最佳答案

onClick参数不接受可组合函数。
删除 @Composable showMessage 中的注释.
使用类似的东西:

@Composable
fun Toolbar() {

val context = LocalContext.current

TopAppBar(title = {},
actions = {
IconButton(onClick = {
showMessage(context, message = "test")
}){}
})
}

fun showMessage(context: Context, message:String){
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}

关于android - @composable 调用只能在 @composable 函数的上下文中发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63801346/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com