Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does calling setOnClickListener from multiple classes result in only one callback?

I'd like to be able to change OnItemClickListener for a ListView dynamically. However, the API isn't clear about whether or not this is acceptable, nor about what the outcome will be if I do.

What I would like is that if I call listView.setOnItemClickListener() from one class, and then later again from a different class, that only the more recent class gets the callback.

This question incidentally could also apply to SetOnClickListener().

The API might be implemented to behave this way, but it might instead be implemented such that all classes that called setOnItemClickListener get the callback.

Which behavior is actually implemented by the Android API?

like image 764
Jeff Axelrod Avatar asked Mar 27 '12 01:03

Jeff Axelrod


1 Answers

Check out the AdapterView.setOnItemClickListener() source code here:

/**
 * Register a callback to be invoked when an item in this AdapterView has
 * been clicked.
 *
 * @param listener The callback that will be invoked.
 */
public void setOnItemClickListener(OnItemClickListener listener) {
    mOnItemClickListener = listener;
}

In Java world, generally a setter method will flush the previous value and set the object's instance variable to the new value. So the behavior you are talking about is only the more recent class gets the callback.


it might instead be implemented such that all classes that called setOnItemClickListener get the callback.

In Java world, this is also possible, in this case, as a good OOP practice, we usually name it addOnItemClickListener(), which is more specifically, use a List of Listener store/manage multiply listeners within the actual implementation. This is not how AdapterView.setOnItemClickListener() is implemented in API.

like image 57
yorkw Avatar answered Sep 25 '22 13:09

yorkw