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?

有帮助吗?

解决方案

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

其他提示

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);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top