简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM