Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android setOnItemClickListener vs setOnClickListener

As I know, there are two methods to handle click on different list items:

  1. Use setTag() to set types for items of list in Adapter, then setOnItemClickListener() for the list and getTag() of the view to differentiate the type, like this:

listview.setOnItemClickListener(new OnItemClcikListener(){});

  1. Inside the adapter, setOnClickListener() individually for each item during getView(), like this:

item.setOnClickListener(new OnClickListener() {});

What is the difference and which one is preferred?

like image 402
GilbertLee Avatar asked Oct 20 '22 18:10

GilbertLee


1 Answers

OnItemClickListener is very easy to manage compare to OnClickListener. If you still would love to manage OnClickListener I will tell why OnItemClickListener is much better than OnClickListener.

Once you start scrolling ListView items will start getting reused and you ended up creating lot of OnClickListener. Don't worry, this is not a memory leak as GC will come into picture and collect those but you should not feel safe also because GC pauses your activity even if it is fraction of second that's considerable.

So would I go with OnItemClickListener unless you planned something different for individual list item.

If you need to create specific portions of each item to be clickable or want more than one action to be performed for a given item, it would be best if possible to collect those actions into a single OnClickListener that is created once and then attached to each item in getView(). You can differentiate which item was clicked by attaching metadata about the click action and maybe list position to the views themselves with setTag().

like image 132
Praveena Avatar answered Oct 22 '22 07:10

Praveena