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

Android Basic Alert Dialog Box
Basic CardView

Basic CardView

Material Design.

Rounded Corners with a Border
Rounded Button in Android Studio

Rounded Button in Android Studio

Create beautiful buttons in XML.

RecyclerView Day 3: Invoicing app

RecyclerView Day 3: Invoicing app

Built with Android Studio and Kotlin.

Build a Ridesharing Android App - Part 1

Build a Ridesharing Android App - Part 1

Getting started is sometimes the hardest part.

setOnClickListener

Add a click listener in Kotlin.

Android Login Layout

Let users sign in.

Registration Screen

Registration Screen

It always begins with registration.