An onclick listener in Android are one of those things that used to take up a lot of lines, even if the important portion of the code was only one line. Kotlin simplifies Android framework a lot, and one of the best improvements is onClickListener
. In this recipe, we will see how we can simplify the traditional lengthy click listeners with the help of lambdas.
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.
Let's follow the given steps to understand how to use click listener using lambdas:
- Let's start with creating an activity with some view, such as a button on which we can attach an
onClickListener
. Check out the following XML layout for one possible activity layout:
<?xml version="1.0" encoding="utf-8"?> <android...