Question

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?

Was it helpful?

Solution

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();}
    }
}

OTHER TIPS

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top