Add a click listener in Kotlin.

When we want a screen press to trigger an event, we can use an OnClickListener. For example, if we have a Button, we can listen for when the user presses it. In XML, here is our Button:

        android:text="Sign in"
        app:layout_constraintTop_toBottomOf="parent" />

Most importantly, this Widget has an id of submitButton. With the layout in place, we can add a listener in MainActivity.

        submitButton.setOnClickListener {
            submitButton.text = "Thanks :)"

In the above code, we listen for a click on submitButton. When the user presses it, we change the Button's text to Thanks :).

We can take this a step further. We can create a new method called goToProductsScreen inside onCreate. Then we need to create the goToProductsScreen method:

    private fun goToProductsScreen() {
        submitButton.setOnClickListener {
            submitButton.text = "Thanks :)"

Hopefully you learned something in this tutorial, and I'll see you in the next tutorial!

More Tutorials

Build an Android Ecommerce App in Kotlin - Part 21

Build an Android Ecommerce App in Kotlin - Part 20

Build an Android Ecommerce App in Kotlin - Part 19