How to Handle OnClick Listener using When keyword in Android?
Last Updated :
28 Apr, 2025
In this article, we are going to see how can we apply the OnClick event to a button in android with the help of When Keyword, we can also apply the onClick event to a button in various other ways such as by setOnClickListener and findViewById, by ViewBinding but all these methods are taken a long time to implement and decrease our development speeds, so to overcome these problems we are going to handle OnClick Listener by the Help of When keyword and with the help of View. which makes it super easier and increases our development speed.
When Keyword: It is very similar to Switch Case in other languages, it executes a block of code when an specified condition is Satisfied .
To implement this first we have to Implement View.OnClickListener in your Activity or Fragment, you have to override the OnClick method on our class.
Step-By-Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. The Code is given in Kotlin language so make sure that you select Kotlin language for your project.
Step 2: Change the StatusBar Color
Navigate to app > res > values > themes > themes.xml and add the below code under the style section in the themes.xml file.
<item name="android:statusBarColor" tools:targetApi="l">#308d46</item>
Step 3: Working with activity_main.xml
Navigate to the app > res > layout > activity_main.xml and add the below code to the activity_main.xml file. Below is the code for the activity_main.xml file. The activity_main.xml represents the UI part of our application. It Includes two Buttons on which we are going to apply OnClick Listener and a TextView that displays which Button is clicked by the user.
XML
<?xml version="1.0" encoding="utf-8"?>
<!-- LinearLayout orientation vertically !-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<!-- TextView to display which button is click by the user !-->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:text="Text"
android:id="@+id/tv_display"
android:gravity="center"
android:layout_gravity="center"
android:layout_marginTop="100dp"
android:textStyle="bold"
android:textColor="@color/black"
android:textSize="20sp" />
<!--Button 1 !-->
<Button
android:layout_width="180dp"
android:layout_height="40dp"
android:text="Button 1"
android:id="@+id/btn1"
android:layout_gravity="center"
android:layout_marginTop="190dp" />
<!--Button 2!-->
<Button
android:layout_width="180dp"
android:layout_height="40dp"
android:text="Button 2"
android:id="@+id/btn2"
android:layout_gravity="center"
android:layout_marginTop="50dp" />
</LinearLayout>
Step 4: Working with MainActivity File
In this step, we are going to apply the OnClick listener to our two buttons with the help of the when keyword. At first, we have to implement View.OnClickListener to our MainActivity class.
class MainActivity : AppCompatActivity() , View.OnClickListener
Then we have to override the onClick method in our MainActivity class. Then in the onClick method, we are going to use our when keyword. Go to the MainActivity File (Navigate to app > java > YourPackageName > MainActivity) and follow the below code. Comments are added inside the code for a better understanding of the Code.
Kotlin
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
class MainActivity : AppCompatActivity() , View.OnClickListener {
// Implementing View.OnclickListener
var tv:TextView?=null
var btn1:Button?=null
var btn2:Button?=null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
tv=findViewById(R.id.tv_display)
btn1=findViewById(R.id.btn1)
btn2=findViewById(R.id.btn2)
btn2?.setOnClickListener(this) // Applying onCLick Listener to the button
btn1?.setOnClickListener(this) // Applying onCLick Listener to the button
}
// Overriding onClick Method in our Class
override fun onClick(view: View?) {
// passing the id of the button that was clicked by the user
when(view!!.id){
// when button 1 is clicked then execute this block of code
R.id.btn1->{
Toast.makeText(this,"Button 1 is clicked",Toast.LENGTH_SHORT).show()
tv?.setText("Button 1 is clicked") //Assign the text to the textview
}
// when button 2 is clicked then execute this block of code
R.id.btn2->{
Toast.makeText(this,"Button 2 is clicked",Toast.LENGTH_SHORT).show()
tv?.setText("Button 2 is Clicked") // Assign the text to the textview
}
}
}
}
Java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
// Implementing View.OnclickListener
private TextView tv;
private Button btn1;
private Button btn2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = findViewById(R.id.tv_display);
btn1 = findViewById(R.id.btn1);
btn2 = findViewById(R.id.btn2);
btn2.setOnClickListener(this); // Applying onClick Listener to the button
btn1.setOnClickListener(this); // Applying onClick Listener to the button
}
// Overriding onClick Method in our Class
@Override
public void onClick(View view) {
// passing the id of the button that was clicked by the user
switch(view.getId()) {
// when button 1 is clicked then execute this block of code
case R.id.btn1:
Toast.makeText(this,"Button 1 is clicked",Toast.LENGTH_SHORT).show();
tv.setText("Button 1 is clicked"); //Assign the text to the textview
break;
// when button 2 is clicked then execute this block of code
case R.id.btn2:
Toast.makeText(this,"Button 2 is clicked",Toast.LENGTH_SHORT).show();
tv.setText("Button 2 is Clicked"); // Assign the text to the textview
break;
}
}
}
Output:
Similar Reads
How to Enable/Disable Click Listener on Views in Android? Sometimes, when we come across a situation where we need not want to click on some clickable views. Like if mandatory data is not filled in by the user, So in that situation it is very helpful to have a clicks control over our views. So in this article, we will learn how to disable/enable click list
2 min read
How to Use Static Method in Android? Android is an open-source operating system, based on the Linux kernel and used in mobile devices like smartphones, tablets, etc. Further, it was developed for smartwatches and Android TV. In this article, we are going to see how we can implement static methods in Android. We will be creating static
5 min read
How to Build a Simple Torch App in Android using Kotlin? Torch Application is a very basic application that every beginner level android developer should definitely try to build while learning Android. In this article, we will be creating an application in which we will simply display a toggle button to switch on and switch off the torch. Note: If you are
4 min read
How to Close or Hide Android Soft Keyboard with Kotlin? Many times there is a need in which we have to close the android soft keyboard programmatically when the user has typed some text within the edit text. This type of functionality is generally required in four digits pins in which after users type 4 digit pin the keyboard will be closed programmatica
3 min read
How to Apply OnClickListener to RecyclerView Items in Android? As we know applying OnClickListener to a Button is very simple but applying OnClickListener to a RecylerView item is different. In this article we first create a RecylerView when we click a particular item of the RecyclerView then a new activity will be shown and display the name and email of the pa
12 min read
How to Use Phone Selector API in Android? Phone Selector API is used to detect phone numbers being used in the phone. Using this you can avoid manual input of Phone Numbers by users and prompt them to choose the desired number. A sample image is given below to get an idea about what we are going to do in this article. Note that we are going
3 min read
How to add TextSwitcher with animation in Android using Java A TextSwitcher is used to animate a text on a screen. It is the child class of the ViewSwitcher class. It contains only one child of type TextView. In order to set animation on TextSwitcher we have to add animation tag or we can add programmatically. Here are the some usage of TextSwitcher: Changing
2 min read
How to Display a Text in a Specific Time in Android using Handler? The Handler class in Android is a fundamental component that facilitates communication and synchronization between different threads, particularly between background threads and the main UI thread. It offers a powerful mechanism for executing code at specific times or after specific delays, enabling
3 min read
How to Apply onClickListener on Menu Item in Android? In the context of Android development, a "menu item" refers to an individual item in a menu. A menu is a visual element in an Android app that provides a set of options to the user, allowing them to perform various actions or navigate to different parts of the app. A menu item is typically represent
5 min read
How to Open a Specific Folder Via Intent in Android? In this article, we are going to open a specific folder from our App. This feature is useful in many cases. Most of the time when we want to upload any file then the app simply opens the file manager. But we can implement this feature for effective use like whenever any user wants to upload any file
3 min read