Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

You are free to setOnItemClickListener() as many times as you like, only the most recent OnItemClickListener will be used.

String className = "MyOnClickListener";
obj = (OnClickListenerInterface)( Class.forName( className).newInstance() );

You will have to create an interface for the listener but you can implement the different listener in different clasess, and then called each one of them dynamically like is shown in this code portion.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top