Search code examples
androidandroid-listviewonclicklisteneronitemclicklistener

Android ListView ClickListener


I have a question regarding the best practice of creating a click listener for a list view with custom adapter. So, my question is: Where is better to implement the click listener? In the custom adapter or it's better to implement setOnItemClickListener in the Activity?


Solution

  • AFAIK there is no "best" way to do it. It depends largely on what exactly you are trying to achieve.

    If you only want one individual element within the row to be clickable then you'd have to do that inside the Adapters getView() method.

    However if you want the entire row to be clickable then you have the choice of doing it in the getView() method, or inside the Activity with setOnItemClickListener()

    If you want to split hairs about which would be better in the latter case it would depend on a bit on what action is taken when the row is clicked. If it is something arbitrary and small that doesn't require access to many other objects, inside the Adapter will be easy. But if it does require interaction with other objects (i.e. context, data sources etc...) then it might be easier to do it in the Activity if you already have references to that stuff in your Activity. That way you avoid the need to pass all of those things along to the Adapter.