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

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.

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 insert the mobile number on an android application using EditText

Number Insertion in android application: Sometimes while dealing with numbers, we don't want to insert any string inside an number so, we premiliary define an EditText so we externally specify...

2 minutes read.

Android Tutorial

This Android tutorial will provide you with all the concepts that will be beneficial for both beginners and advanced-level students or candidates. You can learn this tutorial to begin your...

6 minutes read.

Android 9.0 Pie vs. Android 10, which one is better

Android smartphone users are always searching for new system upgrades and keep an eye on system updates whenever the next version is published. Android 9 Pie and Android Q 10 are...

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

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.

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.

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

3 minutes read.

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.

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.

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.

Android Styles and Themes

Android styles allow you to design the appearance (for example, colors, size, and fonts) of Android UI components from XML resource files. With this method, you only need to set...

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

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.

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.

Broadcast Receiver in Android with Example

When a device wakes up, receives a message, receives an incoming call, switches to aeroplane mode, or initiates any other system-wide action, it is said to have been broadcast in...

5 minutes read.