4

I know that the base different is that setId() takes int as a parameter, while setTag() takes Object. I am asking more about practical advice.

When I generate more same elements programmatically, I set their IDs via setId(++counter) and that is fine for me to know which element has sent the onClick event. And I could do the same thing via setTag(++counter), but I am used to the previous approach.

So when should I use setTag() and am I making a mistake when using setId()?

I guess if my way is right, then I'd use setTag() when I want to pass additional data, but I'll leave you comment on this issue first.

sandalone
  • 41,141
  • 63
  • 222
  • 338

2 Answers2

4

Your guess is right. You should use the setId() when you only want a way to identify that particular View in your code and setTag when you want to pass additional information along with that View(that additional data may or may not uniquely identify that View). You could use only the setTag method and pass a compound object that contains id + additional data but in this situation you are required to build a special object instead of the more simply way, calling the two methods in question.

Edit : The docs for the View class also contain valuable information about those two methods:

IDs

Views may have an integer id associated with them. These ids are typically assigned in the layout XML files, and are used to find specific views within the view tree.

Tags

Unlike IDs, tags are not used to identify views. Tags are essentially an extra piece of information that can be associated with a view. They are most often used as a convenience to store data related to views in the views themselves rather than by putting them in a separate structure.

user
  • 86,916
  • 18
  • 197
  • 190
1

ID is (typically unique) integer type of property which you can assign to any View just to recognize them in future.

TAG is Object type of property which is used to assign additional data (may by your own Object), different Object may carry similar tag.

So if you just want to uniquely identify your Views you should go with id (as it is primitive data type and will consume small amount of memory), whereas if you want your Object to carry additional info also, go with TAG.

Adil Soomro
  • 37,609
  • 9
  • 103
  • 153