Reputation: 36654
I try to add on click listener to my android view.
however, when I add with this code:
public interface SwipeableButtonListener {
public void onClick();
public void onSwipe();
}
private SwipeableButtonListener listener = null;
public void setOnClickListener(SwipeableButtonListener listener) {
this.listener = listener;
}
the current listener is replaced and not a new one is added to the registered one.
how can I change this? creating listener ArrayList is the only way?
does native addOnClickListener override existing listener or adds to a built-in listener list?
Upvotes: 1
Views: 1469
Reputation: 1148
The pattern that I use is along these lines:
private List<SwipeableButtonListener> listeners;
public void addOnClickListener(SwipeableButtonListener listener)
{
if(listeners == null)
listeners = new ArrayList<SwipeableButtonListener>();
listeners.add(listener);
}
private void fireButtonSwipedListeners()
{
if(listeners != null){
for(SwipeableButtonListener listener: listeners){
listener.onSwipe();}
}
}
Upvotes: 1
Reputation: 49817
Try something like this:
public interface SwipeableButtonListener {
public void onClick();
public void onSwipe();
}
private final List<SwipeableButtonListener> swipeableButtonListeners = new ArrayList<SwipeableButtonListener>();
public void addOnClickListener(SwipeableButtonListener listener) {
this.swipeableButtonListeners.add(listener);
}
Upvotes: 1