setOnClickListener

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:

    <Button
        android:id="@+id/submitButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:text="Sign in"
        app:layout_constraintLeft_toLeftOf="parent"
        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

setOnClickListener

Add a click listener in Kotlin.

Android Login Layout

Let users sign in.

Android Studio Tutorial - Part 7 (2019 Edition)

Enhance the RecyclerView.