How to Use setOnClickListener in Kotlin
- Create a New Project and Add a Button in Kotlin
-
Use
setOnClickListener()
Without a Callback in Kotlin -
Use
setOnCliclListener()
With a Callback in Kotlin -
Use
setOnClickListener()
With a Lambda Expression in Kotlin -
Use the
View.OnClickListener
Interface on theMainActivity
Class in Kotlin
The setOnClickListener()
method is an event listener, which means that it will only be invoked when an event such as a button click has occurred. The setOnClickListener()
is a method of the View
class and can be used with any class that inherits from it.
In this tutorial, we will use a Button
to test the method in action. The Button
class inherits the method from the TextView
class, which also inherits the method from the View
base class.
Create a New Project and Add a Button in Kotlin
Go to your development environment and create a new android project with an empty activity. Ensure Kotlin is the selected language for this application.
To create a Button
component, go to the activity_main.xml
file under the Layout folder and paste the following XML code inside the ConstraintLayout
.
<Button
android:text="Click me"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/click_me_btn"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
Use setOnClickListener()
Without a Callback in Kotlin
Go to the MainActivity
class of Kotlin and paste the following code into the onCreate()
method just after the setContentView()
method.
val clickMeBtn: Button = findViewById(R.id.click_me_btn)
clickMeBtn.setOnClickListener {
val toast = Toast
.makeText(applicationContext,
"You have clicked me",
Toast.LENGTH_SHORT).show()
}
The findViewById()
method helps us retrieve the button we have created on our layout using the id unique to that component. This method can retrieve any component that inherits from the View
class because it is a generic method.
The setOnClickListener()
method consumes a callback as an argument, but we directly add the action to be performed inside this method without passing any callback to it.
This is made possible by the @Nullable
annotation added to the method behind the scenes. The annotation indicates the parameter can be optional or null.
Note that when we use the setOnClickListener()
method, it first sets the button to be clickable if it is not clickable.
We have created a text using the makeText()
static method of the Toast
class, and this message will be displayed on the screen for a short period, and then it will disappear.
Run the Application
Press the Run icon located on the top right section of the IDE toolbar to execute the application. The following image shows the position of the Run button.
This will run the application, launch the virtual device, and install it on the virtual device. If you press the button labeled CLICK ME
, a message labeled You have clicked me
will be displayed on the bottom of the screen, as shown below.
Use setOnCliclListener()
With a Callback in Kotlin
As we have mentioned in the previous example, the setOnClickListener()
method has an optional parameter View.OnClickListener
which is a callback for the onClick()
method.
Go to the MainActivity
class and paste the following code into the onCreate()
method just under the setContentView()
method. Ensure you comment on the previous example.
val clickMeBtn: Button = findViewById(R.id.click_me_btn)
clickMeBtn.setOnClickListener(object : View.OnClickListener{
override fun onClick(view: View?) {
val toast = Toast
.makeText(applicationContext,
"You have clicked me",
Toast.LENGTH_SHORT).show()
}
})
In the above example, we have passed the View.OnClickLictener
callback to the method and overridden the onClick()
method.
The onClick()
method has a parameter of type View
, indicating the view clicked. You can use the view inside the onClick()
to execute any method, such as changing the background color.
In this example, we have displayed a Toast
message just like we did in the previous example. Use the same steps as we used to run and test the application, and you will get the same results.
Use setOnClickListener()
With a Lambda Expression in Kotlin
This example is similar to the one we have covered above, but we convert it to a lambda expression instead of overriding the onClick()
method of our callback.
Go to the MainActivity
class and paste the following code into the onCreate()
method just after the setContentView()
method. Ensure you comment on the previous example.
val clickMeBtn: Button = findViewById(R.id.click_me_btn)
clickMeBtn.setOnClickListener(View.OnClickListener { view ->
Toast.makeText(applicationContext,
"You have clicked me",
Toast.LENGTH_SHORT).show()
})
Since we have access to the view
that was clicked, we can execute any method, but we only display a Toast
message in this example.
Use the same steps we used to execute and test the first example, and you will get a Toast
message displayed on the screen, as we have seen in the other examples.
Use the View.OnClickListener
Interface on the MainActivity
Class in Kotlin
The View.OnClickListener
callback is an interface, and we can implement this interface on the MainActivity
class, as shown below.
class MainActivity : AppCompatActivity(), View.OnClickListener {
}
Once we implement the interface, we must implement the onClick()
method inside this class. Copy and paste the following code inside the MainActivity
class.
override fun onClick(view: View?){
when(view?.id){
R.id.click_me_btn -> {
Toast.makeText(applicationContext,
"You have clicked me",
Toast.LENGTH_SHORT).show()
}
}
}
The onClick()
method provides us with access to the clicked view, but since we are not retrieving the component by id, we have to use the when
statement that works the same way as the switch
statement to identify the component that was clicked.
If the id
matches the id of the click_me_btn
, the functionality that follows inside the arrow function is executed. We only display a Toast
message on the screen in this example.
Use the same steps that we have used to run and test the previous examples. This example displays the same results as expected.
David is a back end developer with a major in computer science. He loves to solve problems using technology, learning new things, and making new friends. David is currently a technical writer who enjoys making hard concepts easier for other developers to understand and his work has been published on multiple sites.
LinkedIn GitHub