Difference between set/getId() and set/getTag()?

android, tags

Solution

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.

Problem

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.

Original source

Related problems