Event Handling
The Kotlin API provides a streamlined approach to event handling using lambdas:
- Event handlers in common props - event handlers are configured via
Styleusing lambdas. - Accepting custom event handlers - custom events use lambdas passed as props.
Each of these scenarios is detailed in the following sections.
Supplying event handlers
Event handlers in common props
Event handlers for common interactions (such as clicks) are provided via Style.
Style properties accept lambdas to handle user interactions.
class EventComponent : KComponent() {
override fun ComponentScope.render(): Component? {
return Column(
style = Style.onClick { onClick() }.width(80.dp).height(80.dp).backgroundColor(YELLOW),
)
}
}
private fun onClick() {
Log.d("EventComponent", "click")
}
Accepting custom event handlers
In the Kotlin API, custom event handlers are implemented by accepting a lambda as a prop. The lambda is invoked when the event occurs:
class ClickEventComponent(
private val onButtonClicked: (String) -> Unit,
) : KComponent() {
override fun ComponentScope.render(): Component {
return Column {
child(Text(text = "OK", style = Style.onClick { onButtonClicked("OK clicked") }))
child(Text(text = "Cancel", style = Style.onClick { onButtonClicked("Cancel clicked") }))
}
}
}