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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.