Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Event Handling
2.1.
Concepts Related To Event Management
3.
Methods of Event Listeners & Handlers
4.
Event Listeners Registration
5.
Touch Mode
6.
Handling Focus
7.
Example Application
8.
Frequently Asked Questions
9.
Conclusion
Last Updated: Mar 27, 2024

Event Handling In Android

Author Akshit Pant
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Events are a convenient way to gather information about a user's interactions with interactive components of an application.

In this blog, we will be learning about different-different types of event handlers available on Android.
Before jumping directly on how Android Studio handles the events, first knowing the basic knowledge of Kotlin and how to use it is strongly recommended.

So, let us start reading about how Event Handling works in Android.

Event Handling

There are several ways to intercept events from a user's interaction with your application on Android. When we consider events within our user interface, the approach is to capture them from the View object with which the user interacts. This is made possible through the View class.

You'll see multiple public callback methods for UI events within the various View classes that you'll utilize to assemble your layout. When an action is performed on an object, the Android framework invokes these methods. 

For example, when a View (say Button) is touched, the onTouchEvent() method is called upon that object. However, to intercept this, you must extend the class and override the method. Extending every View object to handle such an event, on the other hand, would be impractical. This is why the View class also includes a set of nested interfaces with callbacks that are considerably easier to define. These interfaces, also known as event listeners, are the key to collecting user interaction with your UI.

NOTE: If we want to extend a View class in order to build a custom component, then we will be able to define the default event behaviors for our class using the class event handlers.

Concepts Related To Event Management

The three topics below are all connected to Android Event Management.

Event Listeners: An event listener is a View class interface that has only one callback method. When the View is activated( to which the listener has been registered) by user interaction with the item in the UI, the Android framework will call these methods.

Event Listeners Registration: The process of registering an Event Handler with an Event Listener so that the handler is called out when the Event Listener fires the event is known as event registration.

Event Handlers: When an event occurs for which we have registered an event listener, the event listener calls the Event Handlers method, which is the function that handles the event.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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

  1. 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.
  2. 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.
  3. 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.

Previous article
Gallery View in Android
Next article
Sliding Drawer in Android
Live masterclass