Handling events in android

Android — Event Handling

Events are a useful way to collect data about a user’s interaction with interactive components of Applications. Like button presses or screen touch etc. The Android framework maintains an event queue as first-in, first-out (FIFO) basis. You can capture these events in your program and take appropriate action as per requirements.

There are following three concepts related to Android Event Management −

Event Listeners − An event listener is an interface in the View class that contains a single callback method. These methods will be called by the Android framework when the View to which the listener has been registered is triggered by user interaction with the item in the UI.

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

Event Handlers − When an event happens and we have registered an event listener for the event, the event listener calls the Event Handlers, which is the method that actually handles the event.

Event Listeners & Event Handlers

This is called when the user either clicks or touches or focuses upon any widget like button, text, image etc. You will use onClick() event handler to handle such event.

This is called when the user either clicks or touches or focuses upon any widget like button, text, image etc. for one or more seconds. You will use onLongClick() event handler to handle such event.

This is called when the widget looses its focus ie. user goes away from the view item. You will use onFocusChange() event handler to handle such event.

This is called when the user is focused on the item and presses or releases a hardware key on the device. You will use onKey() event handler to handle such event.

This is called when the user presses the key, releases the key, or any movement gesture on the screen. You will use onTouch() event handler to handle such event.

This is called when the user selects a menu item. You will use onMenuItemClick() event handler to handle such event.

This is called when the context menu is being built(as the result of a sustained «long click)

There are many more event listeners available as a part of View class like OnHoverListener, OnDragListener etc which may be needed for your application. So I recommend to refer official documentation for Android application development in case you are going to develop a sophisticated apps.

Event Listeners 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. Though there are several tricky ways to register your event listener for any event, but I’m going to list down only top 3 ways, out of which you can use any of them based on the situation.

Using an Anonymous Inner Class

Activity class implements the Listener interface.

Using Layout file activity_main.xml to specify event handler directly.

Below section will provide you detailed examples on all the three scenarios −

Touch Mode

Users can interact with their devices by using hardware keys or buttons or touching the screen.Touching the screen puts the device into touch mode. The user can then interact with it by touching the on-screen virtual buttons, images, etc.You can check if the device is in touch mode by calling the View class’s isInTouchMode() method.

Focus

A view or widget is usually highlighted or displays a flashing cursor when it’s in focus. This indicates that it’s ready to accept input from the user.

isFocusable() − it returns true or false

isFocusableInTouchMode() − checks to see if the view is focusable in touch mode. (A view may be focusable when using a hardware key but not when the device is in touch mode)

onTouchEvent()

Event Handling Examples

Event Listeners Registration Using an Anonymous Inner Class

Here you will create an anonymous implementation of the listener and will be useful if each class is applied to a single control only and you have advantage to pass arguments to event handler. In this approach event handler methods can access private data of Activity. No reference is needed to call to Activity.

But if you applied the handler to more than one control, you would have to cut and paste the code for the handler and if the code for the handler is long, it makes the code harder to maintain.

Following are the simple steps to show how we will make use of separate Listener class to register and capture click event. Similar way you can implement your listener for any other required event type.

Event Handler Event Listener & Description
onClick()
Step Description
1 You will use Android studio IDE to create an Android application and name it as myapplication under a package com.example.myapplication as explained in the Hello World Example chapter.
2 Modify src/MainActivity.java file to add click event listeners and handlers for the two buttons defined.
3 Modify the detault content of res/layout/activity_main.xml file to include Android UI controls.
4 No need to declare default string constants.Android studio takes care default constants.
5 Run the application to launch Android emulator and verify the result of the changes done in the aplication.

Following is the content of the modified main activity file src/com.example.myapplication/MainActivity.java. This file can include each of the fundamental lifecycle methods.

Following will be the content of res/layout/activity_main.xml file −

Here abc indicates about tutorialspoint logo

Following will be the content of res/values/strings.xml to define two new constants −

Following is the default content of AndroidManifest.xml

Let’s try to run your myapplication application. I assume you had created your AVD while doing environment setup. To run the app from Android Studio, open one of your project’s activity files and click Run icon from the toolbar. Android Studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −

Now you try to click on two buttons, one by one and you will see that font of the Hello World text will change, which happens because registered click event handler method is being called against each click event.

Exercise

I will recommend to try writing different event handlers for different event types and understand exact difference in different event types and their handling. Events related to menu, spinner, pickers widgets are little different but they are also based on the same concepts as explained above.

Источник

New Way Handle State, Event With Sealed Classes in Android

Sometimes, we want to represent an Event, a State in Android. Such as handle action click item ViewHolder in RecyclerView , or return state when calling API from the server ( SUCCESS, FAIL, LOADING )… We have a lot of solutions for this case, for example use interface , abstract class , or enum class …

With interface or abstract class , it is cumbersome as well as not suitable for expansion. Enum class is often used to represent a state, however, it can show multi values but only allow a single instance of each value and it cannot contain additional information for each type.

For example we want a return state when calling API from the server with retrofit

The downside here is that we cannot insert additional data into each StateApi type.

Such as ERROR(val exeption: Exption), SUCCESS(val data: Data) …

It’s great to be in Kotlin , Sealed class is the best solution 👌

Intro Sealed classes

“Sealed classes = abstract classes + enum++ classes”

Sealed classes are used for representing restricted class hierarchies, when a value can have one of the types from a limited set, but cannot have any other type

Can be defined Sealed classes is an extension of enum classes , and whereas a subclass of a sealed class can have multiple instances that can contain a state. Each instance of Sealed class can contain its own data

To declare a sealed class , we put the sealed modifier before the name of the class. A sealed class can have subclasses ( object, data class …), but all of them must be declared in the same file as the sealed class itself

The example above: Loading, Success, Error is a instance of StateApi. The special thing here is Success is data class contain params is data: String and Error contain params is an error: Exception . So we can easily return states when request data from API.

A sealed class is abstract by itself, it cannot be instantiated directly and can have abstract members. Sealed classes are not allowed to have non-private constructors

Источник

Handling UI Events

On Android, there’s more than one way to intercept the events from a user’s interaction with your application. When considering events within your user interface, the approach is to capture the events from the specific View object that the user interacts with. The View class provides the means to do so.

Within the various View classes that you’ll use to compose your layout, you may notice several public callback methods that look useful for UI events. These methods are called by the Android framework when the respective action occurs on that object. For instance, when a View (such as a Button) is touched, the onTouchEvent() method is called on that object. However, in order to intercept this, you must extend the class and override the method. Obviously, extending every View object you want to use (just to handle an event) would be obsurd. This is why the View class also contains a collection of nested interfaces with callbacks that you can much more easily define. These interfaces, called event listeners, are your ticket to capturing the user interaction with your UI.

While you will more commonly use the event listeners to listen for user interaction, there may come a time when you do want to extend a View class, in order to build a custom component. Perhaps you want to extend the Button class to make something more fancy. In this case, you’ll be able to define the default event behaviors for your class using the class event handlers.

Event Listeners

An event listener is an interface in the View class that contains a single callback method. These methods will be called by the Android framework when the View to which the listener has been registered is triggered by user interaction with the item in the UI.

Included in the event listener interfaces are the following callback methods:

onClick() From View.OnClickListener. This is called when the user either touches the item (when in touch mode), or focuses upon the item with the navigation-keys or trackball and presses the suitable «enter» key or presses down on the trackball. onLongClick() From View.OnLongClickListener. This is called when the user either touches and holds the item (when in touch mode), 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() From View.OnFocusChangeListener. This is called when the user navigates onto or away from the item, using the navigation-keys or trackball. onKey() From View.OnKeyListener. This is called when the user is focused on the item and presses or releases a key on the device. onTouch() From View.OnTouchListener. This is called when the user performs an action qualified as a touch event, including a press, a release, or any movement gesture on the screen (within the bounds of the item). onCreateContextMenu() From View.OnCreateContextMenuListener. This is called when a Context Menu is being built (as the result of a sustained «long click»). See the discussion on context menus in Creating Menus for more information.

These methods are the sole inhabitants of their respective interface. To define one of these methods and handle your events, implement the nested interface in your Activity or define it as an anonymous class. Then, pass an instance of your implementation to the respective View.set. Listener() method. (E.g., call setOnClickListener() and pass it your implementation of the OnClickListener.)

The example below shows how to register an on-click listener for a Button.

You may also find it more conventient to implement OnClickListener as a part of your Activity. This will avoid the extra class load and object allocation. For example:

Notice that the onClick() callback in the above example has no return value, but some other event listener methods must return a boolean. The reason depends on the event. For the few that do, here’s why:

  • onLongClick() — This returns a boolean to indicate whether you 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 have not handled it and/or the event should continue to any other on-click listeners.
  • onKey() — This returns a boolean to indicate whether you 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 have not handled it and/or the event should continue to any other on-key listeners.
  • onTouch() — This returns a boolean to indicate whether your listener consumes this event. The important thing is that 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 fingure gesture, or the eventual up action event.

Remember that key events are always delivered to the View currently in focus. They are dispatched starting from the top of the View hierarchy, and then down, until they reach the appropriate destination. If your View (or a child of your View) currently has focus, then you can see the event travel through the dispatchKeyEvent() method. As an alternative to capturing key events through your View, you can also receive all of the events inside your Activity with onKeyDown() and onKeyUp() .

Note: Android will call event handlers first and then the appropriate default handlers from the class definition second. As such, returning true from these event listeners will stop the propagation of the event to other event listeners and will also block the callback to the default event handler in the View. So be certain that you want to terminate the event when you return true.

Event Handlers

If you’re building a custom component from View, then you’ll be able to define several callback methods used as default event handlers. In the document on Building Custom Components, you’ll learn see some of the common callbacks used for event handling, including:

  • onKeyDown(int, KeyEvent) — Called when a new key event occurs.
  • onKeyUp(int, KeyEvent) — Called when a key up event occurs.
  • onTrackballEvent(MotionEvent) — Called when a trackball motion event occurs.
  • onTouchEvent(MotionEvent) — Called when a touch screen motion event occurs.
  • onFocusChanged(boolean, int, Rect) — Called when the view gains or loses focus.

There are some other methods that you should be awere of, which are not part of the View class, but can directly impact the way you’re able to handle events. So, when managing more complex events inside a layout, consider these other methods:

  • Activity.dispatchTouchEvent(MotionEvent) — This allows your Activity to intercept all touch events before they are dispatched to the window.
  • ViewGroup.onInterceptTouchEvent(MotionEvent) — This allows a ViewGroup to watch events as they are dispatched to child Views.
  • ViewParent.requestDisallowInterceptTouchEvent(boolean) — Call this upon a parent View to indicate that it should not intercept touch events with onInterceptTouchEvent(MotionEvent) .

Touch Mode

When a user is navigating a user interface with directional keys or a trackball, it is necessary to give focus to actionable items (like buttons) so the user can see what will accept input. If the device has touch capabilities, however, and the user begins interacting with the interface by touching it, then it is no longer necessary to highlight items, or give focus to a particular View. Thus, there is a mode for interaction named «touch mode.»

For a touch-capable device, once the user touches the screen, the device will enter touch mode. From this point onward, only Views for which isFocusableInTouchMode() is true will be focusable, such as text editing widgets. Other Views that are touchable, like buttons, will not take focus when touched; they will simply fire their on-click listeners when pressed.

Any time a user hits a directional key or scrolls with a trackball, the device will exit touch mode, and find a view to take focus. Now, the user may resume interacting with the user interface without touching the screen.

The touch mode state is maintained throughout the entire system (all windows and activities). To query the current state, you can call isInTouchMode() to see whether the device is currently in touch mode.

Handling Focus

The framework will handle routine focus movement in response to user input. This includes changing the focus as Views are removed or hidden, or as new Views become available. Views indicate their willingness to take focus through the isFocusable() method. To change whether a View can take focus, call setFocusable() . When in touch mode, you may query whether a View allows focus with isFocusableInTouchMode() . You can change this with setFocusableInTouchMode() .

Focus movement is based on an algorithm which finds the nearest neighbor in a given direction. In rare cases, the default algorithm may not match the intended behavior of the developer. In these situations, you can provide explicit overrides with the following XML attributes in the layout file: nextFocusDown , nextFocusLeft , nextFocusRight , and nextFocusUp . Add one of these attributes to the View from which the focus is leaving. Define the value of the attribute to be the id of the View to which focus should be given. For example:

Ordinarily, in this vertical layout, navigating up from the first Button would not go anywhere, nor would navigating down from the second Button. Now that the top Button has defined the bottom one as the nextFocusUp (and vice versa), the navigation focus will cycle from top-to-bottom and bottom-to-top.

If you’d like to declare a View as focusable in your UI (when it is traditionally not), add the android:focusable XML attribute to the View, in your layout declaration. Set the value true . You can also declare a View as focusable while in Touch Mode with android:focusableInTouchMode .

To request a particular View to take focus, call requestFocus() .

To listen for focus events (be notified when a View receives or looses focus), use onFocusChange() , as discussed in the Event Listeners section, above.

Источник

Читайте также:  Приставка андроид для тв wildberries
Оцените статью