Save time and effort sourcing top tech talent

Best Ways to Do Event Handling in Android

Jan 28, 2022
hackajob Staff

Ready to learn in detail about Event Handling in Android? Well buckle up as we're diving into the best ways to do Event Handling. What are the event listeners? What are the event handlers? How is an event registered? We'll look at all this and more in today's tech tutorial. Let's get started!

What is an Event in Android?

In Android, when an activity is performed by the user it requires further action from the framework. This is an event. Is it really as simple as that? Yes!

So what does that mean for you and your projects? The system handles these events with its listeners and handlers. They're special methods defined in Android View classes. For example, an activity loads and has a button. When the user clicks it, it will take an action like displaying some text or moving to another view. This response to the event is managed by the event listeners and event handlers. This is one way to intercept events from the user interaction and there's more than one way to intercept events from the user.

To consider different events from the user interface, we take a different approach. So the approach is to capture the events from a specific view object that the user interacts with. The View class provides the functions needed to do that.

Input Event

Several callback methods are useful for different UI events. These methods are called by the framework when their respective actions take place. You do not have to extend the class and override the method to handle such events as it is not practical. Instead, the View class contains a collection of nested interfaces with methods that can be easily defined. We'll get into these interfaces below.

Event Listeners

An event listener is an interface that helps you to capture the user interaction with your UI. It's an interface that is defined in the View class, containing a single callback method. These methods will be called by the framework when the listener for the respective View is triggered with the item in the UI. These are some callback methods included in the event listener interfaces:

onClick()

It is defined in the View class as View.OnClickListener. It's called when the user either touches the item (in touch mode) or focuses upon the item with the navigation keys or presses the suitable “enter” (submit) key.

OnLongClick()

This method is defined in View.OnLongClickListener. It's called when the user either touches and holds the item (in touch mode) or focuses upon the item with the navigation keys or press and hold the “enter” (submit) button.

onFocusChange()

This callback is defined in View.OnFocusChangeListener. It's called whenever the user navigates towards or away from the item by using the navigation keys or trackball.

onKey()

This is defined in View.OnKeyListener. It's called when the user focuses on the item and presses or releases a hardware key on the device.

onTouch()

This callback is defined in View.OnTouchListener. It's called when the user performs a touch event, including a press, a release, or any movement gesture on the screen.

onCreateContextMenu()

This method is defined in View.OnCreateContextMenuListener. It's called when a Context Menu is being generated.


There are several other event listeners included in View class like OnHoverListener, OnDragListener, etc which may be required depending on your application.

Sample Implementation

Here's the example code snippet showing how to register an onClickListener for a button.

protected void onCreate(savedValues: Bundle) {
    /*
	Some code here
    */
    val button: Button = findViewById(R.id.myBtn)
    // Register the onClick listener with the implementation above
    button.setOnClickListener { view ->
        // Some action when the button is clicked
    }
    /*
	Some other code here
    */

}

It's way more convenient to implement OnClickListener as a part of your Activity. This will avoid the use of separate class and object allocation. The following snippet shows how to implement this in your code:

class ExampleActivity : Activity(), OnClickListener {
  
    protected fun onCreate(savedValues: Bundle) {
        val button: Button = findViewById(R.id.myBtn)
        button.setOnClickListener(this)
    }

    // Implement the OnClickListener callback
    fun onClick(v: View) {
        // some action when the button is clicked
    }
}

The above implementation of the onClick() method does not return anything. But it's mandatory sometimes for other event listener callbacks to return a Boolean. Here are the few events explained below:

onLongClick()

It returns a boolean to signify that the event has been consumed and no need to carry out anything further. A true value indicates that the event has been managed and it should stop here, false shows that the event has not been managed and it should pass on to any other listener.

onKey()

A boolean value returned indicates the management of the onKey event. A true value signifies that the event is handled and not to continue with it, false does the opposite.

onTouch()

It returns a boolean to indicate whether your listener consumes this event. This event can have multiple actions that follow each other. So, if you return false when the down action event is received, you indicate that you have not consumed the event and are also not interested in subsequent actions from this event. Thus, you will not be called for any other actions within the event, such as a finger gesture, or the eventual up action event.

Event Handlers

Event handlers are the actual methods that include the action that needs to be taken. When an event happens and the respective listener has registered already, the Event Handlers are called by the listeners. Some of the useful callback methods are defined below:

onKeyUp()

It's invoked by the system when a new key event occurs.

onKeyDown()

It's invoked by the system when a key-down event occurs.

onTrackballEvent()

It's invoked by the system when a trackball motion event occurs.

onTouchEvent()

It ' invoked by the system when some touch event occurs.

onFocusChange()

It's invoked by the system when an item gets into focus or loses focus.


Event Listener Registration

Event Registration is the process in which Event Listeners are registered with Event Handlers. This is important as Handler will work only after the Listener fires an Event. Android Event Listener registration can be done in the following three ways:

  • Directly mentioning them in activity_main.xml
  • Using Activity class that implements a listener interface
  • Using an Anonymous class

And that's it! We've looked at all things Event Handling in Android today, be sure to check out our other Android tutorials here or general tech articles here.

Like what you've read or want more like this? Let us know! Email us here or DM us: Twitter, LinkedIn, Facebook, we'd love to hear from you.