What purpose of setTag() and getTag methods()?
The objective of setTag()
is to allow to store any object.
This object can then be recovered with getTag()
.
When should they be used?
When you want to associate some information to the view. It is an "easy" way to store, in the view, data related to it, instead of putting them in a separate structure.
An example is the implementation of viewholder. It uses the Listview item layout tag to store an object with references to its views.
This will allow you to obtain them without the need to repeatedly use findViewById()
.
setTag() and getTag() have a Overload who receives a Resource id to identify the object, allowing more than one.
To use it you must create a file in the folder res/values
where declares the id’s:
xml ids.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item type="id" name="object1" />
<item type="id" name="object2" />
<item type="id" name="object3" />
</resources>
Note: replace objectX
by any names you want.
The methods are thus used:
view.setTag(R.id.object1, object1);
view.setTag(R.id.object2, object2);
view.setTag(R.id.object3, object3);
....
....
object2 = (...)view.getTag(R.id.object2);