Custom listeners in android

Creating Custom Listeners

The «listener» or «observer» pattern is the most common tegy for creating asynchronous callbacks within Android development. Listeners are used for any type of asynchronous event in order to implement the code to run when an event occurs. We see this pattern with any type of I/O as well as for view events on screen. For example, here’s a common usage of the listener pattern to attach a click event to a button:

This listener is built-in but we can also create our own listeners and attach callbacks to the events they fire from other areas in our code. This is useful in a variety of cases including:

  • Firing events from list items upwards to an activity from within an adapter
  • Firing events from a fragment upwards to an activity.
  • Firing async events from an abstraction (i.e networking library) to a parent handler.

In short, a listener is useful anytime a child object wants to emit events upwards to notify a parent object and allow that object to respond.

Listeners are a powerful mechanism for properly separating concerns in your code. One of the essential principles around writing maintainable code is to reduce coupling and complexity using proper encapsulation. Listeners are about ensuring that code is properly organized into the correct places. In particular, this table below offers guidelines about where different types of code should be called:

Type Called By Description
Intents Activity Intents should be created and executed within activities.
Networking Activity , Fragment Networking code should invoked in an activity or fragment.
FragmentManager Activity Fragment changes should be invoked by an activity.
Persistence Activity , Fragment Writing to disk should be invoked by activity or fragment.

While there are exceptions, generally speaking this table helps to provide guidelines as to when you need a listener to propagate an event to the appropriate owner. For example, if you are inside an adapter and you want to launch a new activity, this is best done by firing an event using a custom listener triggering the parent activity.

There are four steps to using a custom listener to manage callbacks in your code:

Define an interface as an event contract with methods that define events and arguments which are relevant event data.

Setup a listener member variable and setter in the child object which can be assigned an implementation of the interface.

Owner passes in a listener which implements the interface and handles the events from the child object.

Trigger events on the defined listener when the object wants to communicate events to it’s owner

The sample code below will demonstrate this process step-by-step.

First, we define an interface in the child object. This object can be a plain java object, an Adapter , a Fragment , or any object created by a «parent» object such as an activity which will handle the events that are triggered.

This involves creating an interface class and defining the events that will be fired up to the parent. We need to design the events as well as the data passed when the event is triggered.

With the interface defined, we need to setup a listener variable to store a particular implementation of the callbacks which will be defined by the owner.

In the child object, we need to define an instance variable for an implementation of the listener:

as well as a «setter» which allows the listener callbacks to be defined in the parent object:

This allows the parent object to pass in an implementation of the listener after this child object is created similar to how the button accepts the click listener.

Now that we have created the setters, the parent object can construct and set callbacks for the child object:

Here we’ve created the child object and passed in the callback implementation for the listener. These events can now be fired by the child object to pass the event to the parent as appropriate.

Now the child object should trigger events to the listener whenever appropriate and pass along the data to the parent object through the event. These events can be triggered when a user action is taken or when an asynchronous task such as networking or persistence is completed. For example, we will trigger the onDataLoaded(SomeData data) event once this network request comes back on the child:

Notice that we fire the listener event listener.onDataLoaded(data) when the asynchronous network request has completed. Whichever callback has been passed by the parent (shown in the previous step) will be fired.

The «listener pattern» is a very powerful Java pattern that can be used to emit events to a single parent in order to communicate important information asynchronously. This can be used to move complex logic out of adapters, create useful abstractions for your code or communicate from a fragment to your activities.

There are several different ways to pass a listener callback into the child object:

  1. Pass the callback through a method call
  2. Pass the callback through the constructor
  3. Pass the callback through a lifecycle event

The code earlier demonstrated passing the callback through a method call like this:

which is defined in the child object as follows:

If the callback is critical to the object’s function, we can pass the callback directly into the constructor of the child object as an argument:

and then when we can create the child object from the parent we can do the following:

The third case is most common with fragments or other android components that need to communicate upward to a parent. In this case, we can leverage existing Android lifecycle events to get access to the listener. In the case below, a fragment being attached to an activity:

For the full details on this approach, check out the fragments guide.

Источник

Custom Listeners In Android

Listeners are a staple of Android development. They are a very popular way of creating asynchronous callbacks. Listeners are generally used to implement the code that runs when an event occurs.

A common usage of listeners that you likely have come across, if you’re a bit experienced in Android development, is the built-in onClickListener of a button. We usually set the onClickListener on a button, with the code that should run when the button is clicked, which is the event in this case. In Java, it usually looks like this:

But besides what I described above, we can create our custom listeners with callbacks attached to events that are fired from certain areas of our code.

Here are some cases where we might need to create a custom listener:

  • When we need to emit an event up from a fragment to an activity
  • When we need to emit an event up from within an adapter to an activity or fragment

In general, a listener is useful when you have a “child object” and a “parent object” or handler, where a parent object is an object that creates a new instance of the child object. And we have some work that needs to be done in the parent object, but also needs to be done only when a certain event occurs in the child object. So we have to find a way to communicate the fact that the event in question has occurred in the child object, to the parent object.

So how do we create a custom listener?

  1. First, define an interface in the child object (adapter, fragment, POJO). Then define the events that will be fired up to the parent. These events are represented by methods in the interface. An example of how this may look like in Java is:

In the above example, onDataReady(Data data) and onSubmitForm() are method signatures/callbacks that represent events that may occur in the child object.

2. Next, set up a listener variable to store a particular implementation of the callbacks in our interface. The implementation of the callbacks will be defined by the parent object. So inside the child class, you can make the variable as well as a public setter method which allows the listener callbacks to be defined from the parent, like so:

You don’t have to use a setter method, as there are several methods to pass the listener callback implementation into the child object, such as passing it through the constructor or passing it in via a lifecycle event(such as the onAttach() event of a fragment when dealing with activity/fragment communication).

3. Now that we’ve created the listener variable, we can implement the interface on the parent class, override the methods, and put in our implementation of those methods, then set the listener implementation(which is our parent class that implements the interface), on the child object.

The above is a very common way of creating an implementation of the listener in the parent class. Another way of doing the same thing we did above is to create an instance of the custom listener inside the parent class (instead of making the parent class itself implement the interface) and setting that implementation as the custom listener for our child object, like so:

4. Now the child object can fire up events to the parent using the listener, when they happen, and pass along data if any, to the parent object. For example, in the child object, this can look like:

And that’s it, we are done setting up the custom listener! I hope you’re able to start making and using your custom listeners if you haven’t already. Or at least have gained a better understanding of them.

Источник

Как создать собственный интерфейс Listener в android?

Может ли кто-нибудь помочь мне создать пользовательский интерфейс прослушивателя с некоторыми фрагментами кода?

ОТВЕТЫ

Ответ 1

Ответ 2

то в вашем классе скажите Event class

в вашем классе драйвера MyTestDriver

Ответ 3

Я создал Generic AsyncTask Listener, которые получают результат из отдельного класса AsycTask и передают его CallingActivity с использованием обратного вызова интерфейса.

Интерфейс

GenericAsyncTask

Ответ 4

Создайте интерфейс прослушивателя.

И создайте метод setOnCustomClick в другом действии (или фрагменте), где вы хотите применить свой пользовательский прослушиватель.

Вызовите этот метод из своего первого действия и передайте интерфейс прослушивателя.

Ответ 5

В Android вы можете создать интерфейс, такой как Listener, и ваша активность реализует его, но я не думаю, что это хорошая идея. если у нас есть много компонентов для прослушивания изменений их состояния, мы можем создать BaseListener, реализующий интерфейс Listener, и использовать код типа для их обработки. мы можем связать этот метод при создании файла XML, например:

но я не думаю, что это хорошая идея.

Ответ 6

Есть 4 этапа:

1.Создать интерфейсный класс (слушатель)

Интерфейс 2.use в представлении 1 (определить переменную)

3. реализует интерфейс для просмотра 2 (вид 1, используемый в представлении 2)

Интерфейс 4.pass в представлении 1 для просмотра 2

Пример:

Шаг 1: вам нужно создать интерфейс и функцию definde

Шаг 2: используйте этот интерфейс в поле зрения

Шаг 3,4: реализует деятельность

Ответ 7

Простой способ сделать этот подход. Сначала реализует OnClickListeners в вашем классе Activity.

Источник

How and why to use Android Visibility Listeners

The Android UI is built up from Views, and in a regular application, there are usually several of them. To find out which View the user is currently looking at, you need to install Visibility Listeners.

Read below to find out about the different options you have to identify the visibility status of a View.

How To Become Visible

In order for our listeners to work, we must first make sure our View is found in the layout hierarchy. There are two ways this happens:

  1. Your View is already part of your layout as it is defined in an XML file
  2. You created a View dynamically, and you need to add it using the addView method

A View’s visibility status is of Integer type and can have one of three options:

  1. VISIBLE (0) — The View is visible to the user
  2. INVISIBLE (4) — The View is invisible to the user, but still takes up space in the layout
  3. GONE (8) — The View is invisible, and it does not take up space in the layout

Once inside our layout hierarchy, there are a few native options to help us know when our View’s visibility has changed.

onVisibilityChanged

This method is triggered when the visibility of the view or of an ancestor of the view has changed. The status of the visibility is found inside the visibility parameter.

onWindowVisibilityChanged

This method is triggered when the containing window of our View has changed its visibility. This does not guarantee that the window your View is in is visible to the user, as it may be obscured by another window.

Visibility Listeners In Action

To see these two listeners in action, let us create a simple project. We will have a LinearLayout with a TextView and a button. We’ll make the button’s on click action add our custom view to the layout.

Источник

Basic Event Listeners

Event Listening in Android development is largely centered around the View object.

Any View (Button, TextView, etc) has many event listeners that can be attached using the setOnEvent pattern which involves passing a class that implements a particular event interface. The listeners available to any View include:

  • setOnClickListener — Callback when the view is clicked
  • setOnDragListener — Callback when the view is dragged
  • setOnFocusChangeListener — Callback when the view changes focus
  • setOnGenericMotionListener — Callback for arbitrary gestures
  • setOnHoverListener — Callback for hovering over the view
  • setOnKeyListener — Callback for pressing a hardware key when view has focus
  • setOnLongClickListener — Callback for pressing and holding a view
  • setOnTouchListener — Callback for touching down or up on a view

Using Java

In Java Code, attaching to any event works roughly the same way. Let’s take the OnClickListener as an example. First, you need a reference to the view and then you need to use the set method associated with that listener and pass in a class implementing a particular interface. For example:

Alternatively, it is sometimes useful to have your class implement the listener directly, in which case you would add the listener implementation to your class and pass a reference to your class to the set method. For Example:

This pattern works for any of the view-based event listeners.

Using XML

In addition onClick has a unique shortcut that allows the method to specified within the layout XML. So rather than attaching the event manually in the Java, the method can be attached in the view. For example:

Within the Activity that hosts this layout, the following method handles the click event:

In addition to the standard View listeners, AdapterView descendants have a few more key event listeners having to do with their items:

  • setOnItemClickListener — Callback when an item contained is clicked
  • setOnItemLongClickListener — Callback when an item contained is clicked and held
  • setOnItemSelectedListener — Callback when an item is selected

This works similarly to a standard listener, simply implementing the correct AdapterView.OnItemClickListener interface:

This works similarly for the setting up a «long click» where an item is pressed and held down using the OnItemLongClickListener:

Troubleshooting: Item Click Not Firing If the item is more complex and does not seem to be properly responding to clicks after setting up the handler, the views inside the item might be drawing the focus. Check out this stackoverflow post and add the property android:descendantFocusability=»blocksDescendants» to the root layout within the template for the item.

In addition to the listeners described above, there are a few other common listeners for input fields in particular.

  • addTextChangedListener — Fires each time the text in the field is being changed
  • setOnEditorActionListener — Fires when an «action» button on the soft keyboard is pressed

If you want to handle an event as the text in the view is being changed, you only need to look as far as the addTextChangedListener method on an EditText (or even TextView):

This is great for any time you want to have the UI update as the user enters text.

Another case is when you want an action to occur once the user has finished typing text with the Soft Keyboard. Keep in mind that this is especially useful when you can see the virtual keyboard which is disabled by default in the emulator but can be enabled as explained in this graphic.

First, we need to setup an «action» button for our text field. To setup an «action button» such as a Done button on the soft Keyboard, simply configure your EditText with the following properties:

In particular, singleLine and imeOptions are required for the Done button to display. Now, we can hook into a editor listener for when the done button is pressed with:

This is often great whenever a user needs to type text and then explicitly have an action performed when they are finished. There are many imeOptions for different situations.

Similarly to EditText, many common input views have listeners of their own including NumberPicker has setOnValueChangedListener and SeekBar has setOnSeekBarChangeListener which allow us to listen for changes:

Almost all input views have similar methods available.

Источник

Читайте также:  Building android app pdf
Оцените статью