Adding listeners to Anko views
We have event listeners on views in Android. Let's understand how Anko makes this easier by providing us with listener helpers.
Getting ready
I'll be using Android Studio 3 to write code. You can get started by creating a new project in Kotlin with a blank activity in Android Studio 3+, as we won't be using any code from other recipes. You also need an intermediate understanding of Android development. Ensure that you have added Anko layouts dependencies to your project (follow the recipe Setting up Anko library for Anko layouts in gradle, in this chapter).
How to do it…
In the following steps, we will learn how to add an event listener to Anko views:
- 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 thebtn_send
ID:
btn_send.onClick { toast("Hello there we have recorded your message!") }
- The preceding code is the same as this:
var btn = find<EditText>(R.id.btn_send...