是否可以将带有参数的活动函数传递给撰写函数?
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
) {
...
}
答案 0 :(得分:1)
您可以将其作为方法引用传递
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")
}