How to do it…

In the following steps, we will learn how to add an event listener to Anko views:

  1. Let's start with a simple example where we listen for click events on a button. Here's the code for attaching an onClick listener on a button with the btn_send ID:
btn_send.onClick { toast("Hello there we have recorded your message!") }
  1. The preceding code is the same as this:
var btn = find<EditText>(R.id.btn_send)btn.setOnClickListener(object : OnClickListener {    override fun onClick(v: View) {      toast("Hello there we have recorded your message!")    }})
  1. Now, let's create a layout having a button and a rating bar. We will attach an onLongPress listener on the button and an onRatingBarChange listener on the rating bar. Check out this code:
verticalLayout ...

Get Kotlin Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.