What is the difference between Java setonitemclicklistener and only onItemClick
I searched the Internet and read the documents in the Google Android help center, but I still don't know the difference between the two and when to use it? I didn't find any detailed answer after stack overflow
serviceListViewProviderPage.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//something to do
}
});
and
serviceListViewProviderPage.setOnItemClickListener(this);
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//something to do
}
Thank you in advance
resolvent:
The two are the same, but the declaration and usage are different. First, let's see what we're doing
here:
view.setOnItemClickListener(Listener);
You are setting up a listener in your view
After that, you must override the onItemClick method of the onitemclicklistener interface to follow the provided contract and act on the item click
Now look at your code example:
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 declare the listener as an anonymous inner class when you set it as a view
advantage:
>Fast coding
Disadvantages:
>If the logic inside the method is too long or the interface has many methods, it will reduce readability > you can't reuse logic inside the listener > can cause memory leaks (thanks @ Murat K)
Second case
To understand the second, you must see that the code must be within the view that implements adapterview.onitemclicklistener, which is why you can use this code
// here you set the class itself as a listener
serviceListViewProviderPage.setOnItemClickListener(this);
However, as long as you must follow the conventions of the interface, the class must implement the method:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//something to do
}
advantage:
>Readability > reusability
Disadvantages:
>Making view a listener is not my first choice. I prefer to have a class only as a listener and another class only as a view