I searched the internet and read out documents on Google Android Help Centre, But still now I am not clear what the difference between the two and when I will use it at what situation?
I go through stack-overflow not found any detailed answer.
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
}
Thanks in Advance
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:
interface has many methods you will loose readabilityListenerSECOND 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:
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With