What is event handling 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

Источник

LiveData with SnackBar, Navigation and other events (the SingleLiveEvent case)

2021 Update: Working with Kotlin? I recommend you move to Channels! While we write official guidance, check out this👌 post .

A convenient way for a view (activity or fragment) to communicate with a ViewModel is to use LiveData observables. The view subscribes to changes in LiveData and reacts to them. This works well for data that is displayed in a screen continuously.

However, some data should be consumed only once, like a Snackbar message, a navigation event or a dialog trigger.

Instead of trying to solve this with libraries or extensions to the Architecture Components, it should be faced as a design problem. We recommend you treat your events as part of your state. In this article we show some common mistakes and recommended approaches.

❌ Bad: 1. Using LiveData for events

This approach holds a Snackbar message or a navigation signal directly inside a LiveData object. Although in principle it seems like a regular LiveData object can be used for this, it presents some problems.

In a list/detail app, here is the list’s ViewModel:

In the View (activity or fragment):

The problem with this approach is that the value in _navigateToDetails stays true for a long time and it’s not possible to go back to the first screen. Step by step:

  1. The user clicks the button so the Details Activity starts
  2. The user presses back, coming back to the list activity
  3. The observers become active again, after being inactive while activity was in the back stack
  4. The value is still true so the Details activity is incorrectly started again

A solution would be to fire the navigation from the ViewModel and immediately set the flag to false:

However, one important thing to remember is that LiveData holds values but doesn’t guarantee to emit every value that it receives. For example: a value can be set when no observers are active, so a new one will just replace it. Also, setting values from different threads could lead to race conditions that would only generate one call to the observers.

But the main problem with this approach is that it’s hard to understand and plain ugly. How do we make sure the value is reset after the navigation event has happened?

❌ Better: 2. Using LiveData for events, resetting event values in observer

With this approach you add a way to indicate from the View that you already handled the event and that it should be reset.

Usage

With a small change to our observers we might have a solution for this:

Adding the new method in the ViewModel as follows:

Issues

The problem with this approach is that there’s some boilerplate (one new method in the ViewModel per event) and it’s error prone; it’s easy to forget the call to the ViewModel from the observer.

✔️ OK: Use SingleLiveEvent

The SingleLiveEvent class was created for a sample as a solution that worked for that particular scenario. It is a LiveData that will only send an update once.

Usage

Issues

The problem with SingleLiveEvent is that it’s restricted to one observer. If you inadvertently add more than one, only one will be called and there’s no guarantee of which one.

In this approach you manage explicitly whether the event has been handled or not, reducing mistakes.

Usage

The advantage of this approach is that the user needs to specify the intention by using getContentIfNotHandled() or peekContent() . This method models the events as part of the state: they’re now simply a message that has been consumed or not.

In summary: design events as part of your state. Use your own Event wrapper in LiveData observables and customize it to fit your needs.

Bonus! Use this EventObserver to remove some repetitive code if you end up having lots of events.

Источник

Faster Android development with data binding

Jan 19, 2017 · 5 min read

Android Data Binding creates a link between UI layer and the underlying data model that holds the information to display. In normal Android app, it is necessary to find the view and update the content. Every time data changes the User Interface widget (TextView, ImageView etc.) bound to it is needs to be update. Lots of hours were wasted on writing and maintaining trivial and almost useless code occupying tens or even hundreds of lines in almost all Activity.

Android Data Binding l ibrary minimize the code for app logic with its UI view. It eliminates the need for these method calls “findViewById” and “setText.”

The real power of data binding is when the updating of a value occurs at many points in an application code. In that situation, the developer doesn’t have to keep track of all the ways a value can be updated. Using data binding can lead to faster development times, faster execution times and more readable and maintained code.

Android data binding generates binding classes at compile time for layouts.

Getting Ready

The Data Binding Library is available for android platforms from Android 2.1 (API 7) and newer. Add the dataBinding element to your app build.gradle file to enable Data Binding.

Binding Layout and Objects

Binding layout files must be configured slightly differently from default layout files. All layout files that intend to use data binding techniques must have a layout<> root tag.

To bind objects it is required to add data<> tag within the layout tag, before the UI view root. data<> element can have multiple variable<> tag within it that describes a property that can be used within the layout.

Our sample activity_main.xml layout would be looks like:

In the layout above, you can see that used as a root tag and User.java is used as a data object in the tag inside tag. Apart from this TextViews have their text set using data binding “@<>” syntax (@ and @).

Data Binding Activity

Now we have a layout file that is data binding capable. To utilize its data binding ability we have to load it in a different way. With data binding, a Binding class is auto generated from your layout file. By default, Binding class is generated based on the layout file name converted into CamelCase with “Binding” suffix added to it like activity_main.xml will result in a class called ActivityMainBinding.

To associate this generated binding class, need to invoke setContentView of DataBindingUtil class like.

Data binding also do automatic null checks, which is really cool. If you want to access the name, but user is null, how much of pain in the neck would it be to write user null ? null : user.firstName null ? 😕 You don’t want to do that. Now, if contact is null, the whole expression in null.

Источник

Читайте также:  Новогодние обои для андроид вертикальные
Оцените статью