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
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").
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.
@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.
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.
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.
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); } }); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With