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

Top 7 Android App Development Books

Do you want to create Android apps but don't know where to start? One should first be familiar with the basics of Android before we discuss these books. With the...

5 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.

Android Broadcast Receivers

Android applications can send or receive broadcast messages from the Android operating system and other Androidapplications, like the publish-subscribe design pattern. When an event of interest happens,these broadcasts are sent. For...

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 Emulator

A tool for creating Android virtual devices (including software and virtual hardware) on your personal desktop is known as Emulator. We can use these virtual devices as the target device...

4 minutes read.

What is Android Studio

Android Studio powered by the IntelliJ platform is an integrated development environment (IDE) and is officially recognized for developing androidapplications. Its foundation lies on JetBrains' IntelliJ IDEA and is specialized...

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.

Android ListView

A kind of AdapterView that displays a vertical list of scrollable views, each of which is laid out below each other is called ListView. Using adapters, items are inserted into...

4 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.

How to reduce the size of APK in Android

What exactly is an APK file? The full form of APK is Android Package Kit. It is the Android operating system's application file format. We use Android Studio to generate APK...

7 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.

Creating a Calendar View App in Android

This article demonstrates how to make an Android application that uses CalendarView to display the Calendar. It also provides the option to pick the current date and view the date....

3 minutes read.

Assets folder in Android

You might have noticed that unlike the Eclipse ADT (App Development Tools), the Android Studio does not have an Assets folder, which is mainly used to store the web resources...

3 minutes read.

Different Ways to Create aar File in Android Studio

A file called an Android archive file (*.aar) can be created using Android Studio and comprises classes and methods that use related files and classes for Android. The Android library...

4 minutes read.

Difference between android developer and web

From a small business to a big firm, every organization in the world of technology requires a digital market presence and only mobile applications and websites/web applications provide for digital...

4 minutes read.

Android ScrollView

A ScrollView is a view group that is used to create vertically scrollable views in an android application. Only a single direct child can be contained by ScrollView. For placing...

5 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.

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.

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.