如何通过活动的功能来撰写

时间:2020-11-05 09:07:45

标签: android android-jetpack-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
) {
    ...
}

1 个答案:

答案 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")
}