Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between setOnItemClickListener and only onItemClick

Tags:

java

android

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

like image 776
Ramanuj Basu Avatar asked Nov 22 '25 09:11

Ramanuj Basu


1 Answers

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.
like image 120
Jordi Castilla Avatar answered Nov 23 '25 22:11

Jordi Castilla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!