androidkotlinhigh-order-component

Passing lambda function to compose button not calling + Kotlin higher order functions + Compose


`I'm passing lambda code to compose button event which is not executing. In MainScreen() fun I'm passing context to execute Android specific code in top level function for compose. When I'm clicking the button it is executing but passing code to launch the second activity is not executing.

`enter code here

@Composable
fun ManinScreen(context: Context?){
    Column {
        ScreenName(name = "Main Screen")
        ShowDetails{
            // Passing code to execute on click event
            Intent(context, DetailsActivity::class.java).also { i ->
                context?.startActivity(i)
            }
        }
    }
}



@Composable
fun ScreenName(name: String) {
    Text(text = "Hello $name!")
}

@Composable
fun ShowDetails(clickAction: () -> Unit){// Passing code to execute on click event
    Button(onClick = {
        //Click event is triggering when user click the button - Executing
        clickAction // But the code inside function is not executing - Not Executing
    }) {
        Text(text = "Show Details")
    }
}

Can someone help what is the mistake.

Thanks!


On click of button event code needs to be execute.

Solution

  • Change your function to

    @Composable
    fun ShowDetails(clickAction: () -> Unit) {
        Button(onClick = clickAction) {
            Text(text = "Show Details")
        }
    }
    

    Button(onClick ={clickAction}) is not correct method to call function.

    Button(onClick = clickAction) is correct.