Skip to content
Related Articles

Related Articles

Improve Article
Input Events in Android with Example
  • Difficulty Level : Hard
  • Last Updated : 23 Feb, 2021

In Android, there’s quite a method to intercept the events from a user’s interaction with your application. When considering events within your interface, the approach is to capture the events from the precise View object that the user interacts with. The View class provides the means to try to do so. Within the varied View classes that you’re going to use to compose your layout, you’ll notice several public callback methods that look useful for UI events. These methods are called by the Android framework when the respective action occurs thereon object. For instance, when a View (such as a Button) is touched, the onTouchEvent() method is named thereon object. However, to intercept this, you must extend the class and override the method. However, extending every View object to handle such an event would not be practical. This is why the View class also contains a set of nested interfaces with callbacks that you simply can far more easily define. These interfaces, called Event listeners, are your ticket to capturing the user interaction together with your UI.

For Example, if a button is to reply to a click event it must register to look at the .onClickListener event listener and implement the corresponding onClick() callback method. In an application when a button click event is detected, the Android framework will call the onClick() method of that particular view.

Android Event Listeners

Event Listener is an interface within the View class that contains one call-back method. These methods are going to be called by the Android framework when the View which is registered with the listener is triggered by user interaction with the item in UI. Included in the event listener interfaces are the following callback methods:

Methods

Event Listeners



Description

onClick()

View.OnClickListener

This method is called when the user touches the item or focuses upon the item with the navigation-keys or trackball and presses the suitable “enter” key or presses down on the trackball.

onLongClick()

View.OnLongClickListener

This is called when the user either touches and holds the item, or focuses upon the item with the navigation-keys or trackball and presses and holds the suitable “enter” key or presses and holds down on the trackball (for one second).

onFocusChange()



View.OnFocusChangeListener

This is called when the user navigates onto or away from the item, using the navigation-keys or trackball.

onKey()

View.OnKeyListener

This is called when the user is focused on the item and presses or releases a hardware key on the device.

onTouch()

View.OnTouchListener

 This is called when the user acts qualified as a touch event, including a press, a release, or any movement gesture on the screen (within the bounds of the item).

onCreateContextMenu()

View.OnCreateContextMenuListener



This is called when a Context Menu is being built (as the result of a sustained “long click”).

Note:

onClick() callback does not return any value. But onLongClick(), onKey(), onTouch() callback returns a boolean value that indicates that you simply have consumed the event and it should not be carried further; That is, return true to indicate that you have handled the event and it should stop here; return false if you’ve not handled it and/or the event should continue to any other on-click listeners.

Android Event Listener Registration

Event Registration is the process by which an Event Handler gets registered with an Event Listener so that the handler is called when the Event Listener fires the event. This example illustrates how to register an on-click listener for a Button 

Kotlin




protected void onCreate(savedValues: Bundle) {
    ...
    val button: Button = findViewById(R.id.button)
    // Register the onClick listener 
    button.setOnClickListener { view ->
        // do something when the button is clicked
    }
    ...
}

Android Event Handlers

Event Handlers are useful to define several callback methods when we are building custom components from view. Following are some of the commonly used callback methods for event handling in android applications.

Method

Description

onKeyDown()This method is called when a new key event occurs.
onKeyUp()This method is called when a key up event occurs.
onTrackballEvent()This method is called when a trackball motion event occurs.
onTouchEvent()This method is called when a touch screen motion event occurs.
onFocusChanged()This method is called when the view gains or loses focus.

We have learned about Event Listeners, Event Handlers, and their callback methods. Now we will see their implementations in our android application.

Android Input Events Example

Let us see the way to implement Input Events in Android. Note that we are going to implement this project using the Kotlin language. 

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 in Kotlin. Note that select Kotlin as the programming language.

Step 2: Working with the XML Files

To design the UI, code is present under the res\layout folder in the form of XML. They are used in the Activity files and once the XML file is in scope inside the activity, one can access the components present in the XML. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail. 

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
  
    <!-- This is the layout for the
         Button which user will click  -->
    <Button
        android:id="@+id/btnClick"
        android:layout_width="200dp"
        android:layout_height="70dp"
        android:layout_gravity="center"
        android:layout_marginTop="200dp"
        android:text="CLICK ME!"
        android:textSize="18sp"
        android:textStyle="bold" />
      
    <!-- This is the layout for the textView, On Click
         of Button the text will appear on the screen  -->
    <TextView
        android:id="@+id/textResult"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="50dp"
        android:textColor="#86AD33"
        android:textSize="25sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="@id/btnClick" />
  
</LinearLayout>

 
Step 3: Working with the MainActivity File

Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. 

Kotlin




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)
  
        // Register OnClickListener for button
        // call Click Handler method
        findViewById<Button>(R.id.btnClick).setOnClickListener {
            displayTextOnButtonClick(it)
        }
  
        // Register OnLongClickListener for button
        // call Click Handler method
        // Return true to indicate that the event is consumed
        findViewById<Button>(R.id.btnClick).setOnLongClickListener {
            displayTextOnLongButtonClick(it)
            true
        }
    }
  
    // Click handler for the Click me button.
    // Display the text below Click me Button
    // Display text after Button click
    // It has No Return Value
    private fun displayTextOnButtonClick(view: View) {
        val text = findViewById<TextView>(R.id.textResult)
        text.text = "Button Clicked !"
    }
  
    // Click handler for the Click me button.
    // Display the text below Click me Button
    // Display text after Button click for a bit long time (1-2sec)
    private fun displayTextOnLongButtonClick(view: View) {
        val text = findViewById<TextView>(R.id.textResult)
        text.text = "Long Button Clicked !"
    }
}

Output: 

Conclusion 

Android bridges the gap between the user interface and the back end code of the application through the concepts of event listeners and callback methods. The Android View class defines a set of event listeners, which can be registered on view objects. Each event listener also has associated with it a callback method. When an event takes place on a view in a user interface, that event is placed into an event queue and handled on a first-in, first-out basis by the Android runtime. If the view on which the event took place has registered a listener that matches the type of event, the corresponding callback method called. This code then performs any tasks required by the activity before returning. Some callback methods are required to return a Boolean value to point whether the event is consumed or needs to be passed on to any other event listeners registered on the view.

Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!
My Personal Notes arrow_drop_up
Recommended Articles
Page :