Ramanuj Basu Ramanuj Basu - 28 days ago 9
Android Question

What is the difference between setOnItemClickListener and only onItemClick

I am new to Android Development and 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

Answer

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:

  • fast to code

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:

  • readability
  • reusability

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.