As I know, there are two methods to handle click on different list items:
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(){});
setOnClickListener()
individually for each item during getView()
, like this:item.setOnClickListener(new OnClickListener() {});
What is the difference and which one is preferred?
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().
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