Event Handling in Android

Events are a convenient way to gather data about user interactions with interactive elements of your application. Like a button click or a screen touch. A queue of events on a first-in-first-out (FIFO) criteria is maintained by Android Framework. Your program can capture these events and take suitable action based on your needs.

There are 3important things associated with managing Android events:

  • Event listener - An event listener is an interface of the View class with one callback method. The Android framework calls these methods when the View in which the listener is registered is triggered by the interaction between the UI item and the user.
  • Registering an event listener-Event registration is a procedure in which aneventhandler gets registered with the listenerso that it is called when an event listener raises an event.
  • Event Handler-When an event occurs and you register an event listener for the event, the respective event handler is called by the event listener, which is the method that handles the event.

Event Listeners

1. OnClickListener()

This listener is called when the user either taps or touches or focuses upon any view such asImagebutton, card view, image, etc. To handle this event, you can use the onClick() event handler.

2. OnLongClickListener()

This listener is called when the user either focuses or touches or taps upon any view such as button, card view, Imagebutton,etc. for a short durationlike2to3 seconds. To handle this event, you can use onLongClick() event handler.

3. OnFocusChangeListener()

This listener is called when the view loses its focus i.e., the user stops interacting with the view item. To handle this event, you can use the onFocusChange() event handler.

4. OnFocusChangeListener()

This listener is called when the user is focusing on the view and presses or releases a hardware key on the device. To handle this event, you can use onKey() event handler.

5. OnTouchListener()

This listener is called when the user tapsor releases the key, or any movement gesture is noticed on the device’s screen. To handle this event, you can use onTouch() event handler.

6. OnMenuItemClickListener()

This listener is called when the user interacts with a menu item.To handle this event, you can use onMenuItemClick() event handler.

There are many other event listeners that you can use as part of the View class, and you can use them according to your application needs such as OnHoverListener and OnDragListener. Therefore, it is recommended to refer to the official documentation of Android application development when developing sophisticated applications.

Event Listener registration

Eventregistration is the procedure by which an event handler registers with the listener, sothe handlercan be called when the event listener has fired an event. There are many complicated ways to register an event listener with an event, but I'm listing only three here and you may use any one of them depending on your situation.

  • Use of anonymous inner classes
  • Activity classes implement the listener interface.
  • Specify event handlers directly using the layout file activity_main.xml.

The following sections show detailed examples of three scenarios. 

Touch Mode

Users can operate the device using hardware buttonsor keyboard keys, or by tapping on the screen. The device is in touch mode when you use it by touching the screen. Then the user can touch and manipulate virtual buttons or images on the screen, etc. You may check that whether the android device is in touch mode or not by calling the isInTouchMode() method of the View class.

Focus

A view or widget typically displays a highlighting or blinking cursor when in focus. This indicates that you are ready to accept user input.

  • isFocusable()-Returns true or false.
  • isFocusableInTouchMode()-First, make sure that the view is in focus in touch mode. (You can focus on the display when using the hardware keys, but you can't focus when the device is in touch mode.)

Event Handling Example

Here is the main activity file src/com.example.application/ClickActivity.java content: This file contains each of the basic lifecycle methods.

public class ClickActivityextends AppCompatActivity{
int count = 0;
Button inc;
Button dec;
TextViewtxt;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);


txt = findViewById(R.id.countText);


inc= findViewById(R.id.button5);


inc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
                increment();
txt.setText(String.valueOf(count));
            }
        });


dec = findViewById(R.id.button6);
dec.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
                decrement();
txt.setText(String.valueOf(count));
            }
        });
    }

Related Topics

Android Date picker example

How to pick date from the user in Android? Write an android example to pick date from the user and display it. Android provides control for the user to pick a date...

3 minutes read.

How to insert an email in android application in android version 8

Email Address Insertion It is used to insert email adrress from the user in the android application.The only point of difference between an EditText and an Emailtext is that EmailText consisits...

1 minute read.

How to Generate QRCode in Android?

Many apps use QR codes to show data in a way that is machine-readable. Data is represented using these codes in a secure manner such that only computers, not humans,...

4 minutes read.

Android Navigation Drawer

A sliding menu used to show important links in the Android Application is called Navigation Drawer. The navigation drawermakes it easier to navigate between the fragments. It is not displayed...

5 minutes read.

Android Toast

Android is one of the most successful operating systems available in today's world. It is an open-source phone platform, compatible with almost all the devices. There are numerous features and...

3 minutes read.

Button Widget in Android Tutorial

Explanation: Button is a widget under Buttons section which is used to execute specific code. Example: XML file: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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" tools:context=".MainActivity">     <Button         android:id="@+id/button"         android:layout_width="wrap_content"    ...

1 minute read.

Top Programming Languages for Android Development

For mobile apps, there are so many programming languages. You would need to spend days simply researching if you had to pick one from a list of 30 coding languages...

8 minutes read.

Android GridView

Theview group that displays items in a two-dimensional scrolling grid is called GridView. The data isadded into this grid layout from anArray List or database. The adapter class isutilized to...

4 minutes read.

Android EditText

In Android, EditText is a UI widget utilized to allow the user to input or change the text. While using the EditTextwidget in your Android application, you need to use...

4 minutes read.

Content Providers of Android with Example

An essential part of Android that performs the function of a relational database by storing application data is called a content provider. The function of the content provider in the...

13 minutes read.

ImageView Widget in Android

What you should already KNOW? You should be familiar with: 1) Creating, building, and running apps in Android Studio 2) Basics of android widgets Explanation: Image View widget is used to insert the image...

2 minutes read.

Dashboard UI Design in Android

One of the essential components that draw the user’s attentions into the application's operation is the dashboard design. It offers details on the application's general functionality in one location. Imagine...

11 minutes read.

Android Time picker example

How to pick Time from the user in android? Write an android example to pick Time from the user and display the date to the user. Android provides controls for the user...

3 minutes read.

Android TextView

Widgets are user interface (UI) elements that help users to interact with Android applications. It is one of many equipments that can be used to improvise the user interface of...

4 minutes read.

Android Studio's Layout Editor

The Layout Editor allows you to efficiently create layouts by dragging UI elements from the Palette into the visual design editor instead of manually creating the layout XML file by...

8 minutes read.

How to show image on an android application

ImageView Widget in Android What you should already KNOW? You should be familiar with: 1) Creating, building, and running apps in Android Studio 2) Basics of android widgets   Explanation: Image View widget is used...

2 minutes read.

How to crop Image from Camera and Gallery in Android?

In this tutorial, we'll learn how to crop photos in the Android Gallery and Camera. There is no crop feature in this project, contrary to what was covered in the...

5 minutes read.

AdapterViewFlipper in Android with Example

The AdapterViewFlipper class, a subclass of the ViewAnimator class, is what we use to switch from two or multiple views when only one is present at a time. The AdapterViewFlipper...

10 minutes read.

Android Activity

What is an Activity? Android Activity is a screen in the user interface of an Android application. In this way, Android activity is very similar to the desktop application window. An...

4 minutes read.

Jetpack Architecture Components in Android

A collection of software elements, libraries, tools, and instructions is called Android Jetpack. It is available to assist in creating reliable Android applications. Jetpack, which was introduced by Google in...

8 minutes read.