Methods of Event Listeners & Handlers
As mentioned earlier, an event listener is a View class interface that has only one callback method. The following callback methods are included in the event listener interfaces:
- onClick(): This(from View.OnClickListener) is called when the user either clicks or focuses upon any widget like Button, image, etc. To handle such an event, we'll utilize the onClick() event handler.
- onLongClick(): This(from View.OnLongClickListener) is called when the user either clicks or focuses upon any widget like button, text, image, etc., for one or more than one second. We'll utilize the onLongClick() event handler to handle such an event.
- onFocusChange(): When the widget loses attention, i.e., when the user moves away from the view item, this(View.OnFocusChangeListener) is called. You'll utilize the onFocusChange() event handler to handle such an event.
- onKey(): When a user is focused on an item and presses or releases a hardware key on the device, this is referred to as this(View.OnKeyListener). We'll utilize the onKey() event handler to handle such an event.
- onTouch(): When a user pushes a key, releases it, or makes any other movement action on the screen, this is referred to as this(View.OnTouchListener). We'll use the onTouch() event handler to handle such an event.
- onMenuItemClick(): This is called when the user picks a menu item. We will use onMenuItemClick() event handler to handle such events.
- onCreateContextMenu(): This(View.OnCreateContextMenuListener) is called out when a Context Menu is being built (that too as a result of sustained "long click").
Event Listeners Registration
It is the process by which an Event Handler registers with an Event Listener so that handler is called when the Event Listener executes the event. Even though there are various challenging ways to register your event listener for each event, I'm simply going to discuss the top three, which you may use in any case.
- By Using an Anonymous Inner Class
- The Listener interface is implemented by the Activity class.
- Using activity_main.xml layout file to specify event handler explicitly.
Touch Mode
Users can interact with their devices by touching the screen or via hardware keys or buttons. Touching the screen activates touch mode on the device. The user interaction can be done with it by touching virtual buttons, photos, and other elements on the screen. The isInTouchMode() function of the View class can be used to determine whether the device is in touch mode.
Handling Focus
When a view or widget is in focus, it is usually highlighted or has a flashing cursor. This means that it is ready to receive user input.
- isFocusable(): It returns a boolean value(true or false).
- isFocusableInTouchMode(): It checks if the View is focusable in touch mode. (Because when using a hardware key, a view may be focusable, but not when the device is in touch mode).
Also, to change whether a View can take focus or not, call setFocusable() method. Focus movement is based on an algorithm that finds the closest neighbor in a given direction.
Note: Activities don't assign an initial focus on devices running Android 9 (API level 28) or higher. If you want to request an initial focus, you must do so explicitly.
Now, let us see the implementation of Event Handling with a working example given below.
Example Application
In this example, to register and collect click events, we'll utilize a separate Listener class. You may implement your listener in the same way for any other required event type.
So open up Android Studio, start an empty activity, give a name to your app(Event Handling CN in our case), and let Android do the Gradle syncing.
Now make the activity_main.xml file as per the need of your desired layout.
Code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv_heading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="@string/event_handling_coding_ninjas"
android:textSize="25sp" />
<TextView
android:id="@+id/tv_Code_Studio_heading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/tv_heading"
android:layout_marginTop="25dp"
android:layout_centerHorizontal="true"
android:layout_marginBottom="40dp"
android:text="@string/code_studio"
android:textColor="#FF6535"
android:textSize="30sp" />
<ImageButton
android:id="@+id/code_studio_img"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_centerInParent="true"
android:src="@drawable/my_img" />
<Button
android:id="@+id/small_font_bttn"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="@+id/code_studio_img"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:background="@android:color/holo_orange_dark"
android:padding="5dp"
android:text="@string/reduce_the_font" />
<Button
android:id="@+id/large_font_bttn"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:padding="5dp"
android:layout_marginTop="8dp"
android:layout_below="@+id/small_font_bttn"
android:layout_alignEnd="@+id/small_font_bttn"
android:background="@android:color/holo_orange_dark"
android:text="@string/increase_the_font" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/large_font_bttn"
android:layout_centerHorizontal="true"
android:text="@string/hey_ninja"
android:textSize="30sp" />
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
strings.xml
<resources>
<string name="app_name">Event Handling CN</string>
<string name="hey_ninja">Hey Ninja!</string>
<string name="increase_the_font">Increase the font</string>
<string name="reduce_the_font">Reduce the font</string>
<string name="code_studio">Code Studio</string>
<string name="event_handling_coding_ninjas">Event Handling Coding Ninjas</string>
</resources>
MainActivity.kt
package com.akshitpant.eventhandlingcn
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val b1 = findViewById<View>(R.id.small_font_bttn) as Button
val b2 = findViewById<View>(R.id.large_font_bttn) as Button
b1.setOnClickListener { v: View? ->
val my_tv1 = findViewById<View>(R.id.textView) as TextView
my_tv1.textSize = 20f
}
b2.setOnClickListener { v: View? ->
val my_tv2 = findViewById<View>(R.id.textView) as TextView
my_tv2.textSize = 40f
}
}
}
Run this code in your Android Studio and connect it with your emulator.
Output:
Now, open up the application and try to click on two buttons(REDUCE THE FONT button & INCREASE THE FONT button), one by one and we will see that font of the “Hey Ninja!” text will change. This happened because each click event triggers the call to the registered click event handler method. In a similar fashion, we can try to write different event handlers for different event types(like menu, spinner, pickers widgets).

Check this out : usb debugging
Frequently Asked Questions
-
What are the various methods for dealing with events on Android?
Some of the most typical callbacks for event handling are:
onKeyDown(int, KeyEvent): This function is called when a new key event happens.
onKeyUp(int, KeyEvent): This function is called when a key-up event happens.
onTrackballEvent(MotionEvent): This function is called when a trackball motion event occurs.
onTouchEvent(MotionEvent): When a touch screen motion event happens, this method is called.
-
In the choice menu, which method is utilized to handle events?
The onPrepareOptionsMenu() method can be used to change the options menu based on events that occur during the activity lifetime.
-
In the context of event handling, what is the listener?
When an event occurs, a listener object is notified. It has two main requirements; first, it must have been registered with one or more sources to receive notifications about certain events kinds. Second, it must implement methods for receiving and processing these notifications.
Conclusion
This article taught us about Event Handling, different modes, and their implementation.
You can head over to our Android Development Course on the Coding Ninjas Website to dive deep into Android Development and build future applications.
We hope this article has helped you enhance your knowledge of the Android Listeners, Handlers, and Registration. If you want to learn more, check out our Programming Fundamentals and Competitive Programming articles. Do upvote this article to help other ninjas grow.