Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attaching multiple listeners to views in android?

Is it possible to attach multiple onClick listeners to buttons in android? Example:

btn1.setOnClickListener(listener1); btn1.setOnCliclListener(listener2); 

And when the button is clicked onClick event of both listener1 and listener2 are triggered?

In normal GUI applications I know that we can attach more than one event handler for an event. Is it possible for android too or is there any restrictions?

Regards, Lalith

like image 721
Lalith Avatar asked Dec 27 '10 23:12

Lalith


People also ask

Can multiple listeners be attached to an event?

You can do how ever you want it to do. They don't have to be together, it depends on the context of the code. Of course, if you can put them together, then you should, as this probably makes the structure of your code more clear (in the sense of "now we are adding all the event handlers").

Can you add two event listeners to the same button?

The addEventListener() methodYou can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements.

Can a class implement multiple listener interfaces?

@Xsmael In Java you are allowed to implement multiple interfaces. And yes, I would say that this is a perfectly acceptable practice. Here you could use anonymous inner classes for the listeners too, but that's just a matter of code style, either style is fine in practice.

How can we implement more than one listener in Java?

All you have to do to work with multiple listeners is: Create a class that extends JFrame and implements ActionListener . Create an number of these JFrames and put them in an array. This array could easily hold any class as long as it implements the ActionListener interface.


2 Answers

Android only supports one registered listener in general. However, you can easily create a listener that simply forwards the events to other listeners using the composite pattern.

like image 186
CommonsWare Avatar answered Sep 28 '22 02:09

CommonsWare


Should someone bump into a similar problem, try this out:

private void setClickListeners(View view, List<View.OnClickListener> clickListeners){     view.setOnClickListener(v -> {         for(View.OnClickListener listener: clickListeners){             listener.onClick(v);         }     }); } 
like image 20
John Kamau Avatar answered Sep 28 '22 03:09

John Kamau