gpt4 book ai didi

android - 如何传递 Activity 的功能来撰写

转载 作者:行者123 更新时间:2023-12-04 23:55:04 24 4
gpt4 key购买 nike

有没有办法将带有参数的 Activity 函数传递给 compose 函数?

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyTheme {
Main(
activityFunWithParam = activityFunWithParam // not work
)
}
}
}

fun activityFunWithParam(param: Param) {
...
}
}

@Composable
fun Main(
activityFunWithPara: (Param) -> Unit
) {
...
}

最佳答案

您可以将其作为方法引用传递

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Main(activityFunWithParam = ::activityFunWithParam)
}
}

fun activityFunWithParam(param: Int) {
Toast.makeText(this, param.toString(), Toast.LENGTH_SHORT).show()
}
}

@Composable
fun Main(
activityFunWithParam: (Int) -> Unit
) {
activityFunWithParam(5)
Text(text = "Test")
}
在您的示例中,方法名称本身不是函数。见 https://kotlinlang.org/docs/reference/lambdas.html#instantiating-a-function-type

关于android - 如何传递 Activity 的功能来撰写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64694134/

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