Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of the View's setTag method?

Tags:

android

I am implementing a ListView using custom adapters. To improve the performance I am returning the newly inflated View if convertView is null, else returning the recycled View.

Now in this process I used the ViewHolder pattern and used the setTag() method of the View. Initially I thought this is some kind of bookmarking but I've not completely understood the use of it. I've checked different blog post where they just used this in the code.

Can someone please explain me the use of the setTag() method?

like image 430
droidsites Avatar asked Nov 08 '11 23:11

droidsites


1 Answers

Basically you can store any kind of object as tag (and cast it back when calling getTag). This can be a simple ID or some complex data. It's some information which you associate with this view.

In the case of lists and the view holder pattern it's a simple object which contains references to views of the tagged view (group). So you don't have to call findViewById every time when you're updating the content of the view. It's just an performance optimization.

Can we store data of list item in the view tag?
No. Because of view recycling you have (e.g.) 10 views which are reused for 1000 list items. Storing data in the tag makes no sense here. It's better to use an custom data object to store the list item state (probably the same array which contains the displayed data) or you persist it right away on list item change.

See also setTag documentation.

like image 122
Knickedi Avatar answered Oct 05 '22 08:10

Knickedi