How to pass activity’s function to compose

You can pass it as a method reference

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

In your example, method name itself is not a function. See https://kotlinlang.org/docs/reference/lambdas.html#instantiating-a-function-type

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top