Both are same but different declarations and uses. First, lets see what we are doing.
Here:
view.setOnItemClickListener(Listener);
You are setting a listener in your view.
After, you must override the method onItemClick
of the OnItemClickListener
interface in order to follow the contract provided and make an action on item click.
Now see your code examples:
FIRST CASE
// set a listener to your wiew
serviceListViewProviderPage.setOnItemClickListener(
// create a new OnItemClickListener
new AdapterView.OnItemClickListener() {
@Override
//
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//something to do
}
});
Here you're declaring the listener as a anonymous inner class at time you set it to your view.
PROS:
CONS:
- if the logic inside the metod is too long or the
interface
has many methods you will loose readability
- you cannot reuse the logic inside the
Listener
- can cause memory leaks (thanks to @Murat K)
SECOND CASE
To understand second one you must see the code MUST be inside a View
that implements AdapterView.OnItemClickListener
, that's why you can use this
// here you set the class itself as a listener
serviceListViewProviderPage.setOnItemClickListener(this);
But, as long as you must follow the contract of the interface, the class must implement the method:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//something to do
}
PROS:
CONS:
- make a
View
be also a Listener
is not my prefered way, I like more to have a class that is only a Listener
and another is only a View
.