开发者

Android: What care should I take when using a View's setTag() property?

Because Java uses object references and not objects themselves, what prevents me from using setTag() to tag a view with an entire object instead of an object's property? Is it just the attribute lookup t开发者_如何学Pythonime when trying to resolve one of the attributes after the getTag() call or is there any other specific thing I should be concerned about?

As for my specific problem, I am using a custom listview that has an imageview and a textview. Initially I bind the listview to a custom adapter to fetch some xml data and then use certain tags inside each item's xml to populate my listview. So the "entire object" I was referring to was the parsed version of the entire XML of an item...


One of the most popular uses of the setTag(Object) method is exactly keeping a reference to a class instance - if you have used custom ListView and custom Adapter, you should know about the ViewHolder pattern.

Without knowing much about your particular problem, I would say - Is this dangerous sometimes? Yes, if used irresponsibly. Does this mean you should avoid it at any cost? No, absolutely not.

Edit: Why do you want to have the parsed data for your views bound to them?

Do you really need it, or you can populate some type of a model? If you want to access the tag of a view in a context, where your view doesn't carry the same meaning/position (like the convertView does in our favorite ViewHolder example :)), I would think using tags is OK.

Otherwise, I'm sure that if you give it a little more thought, you'll find another approach better suited for your problem.


There are two api for settag one with just value and another with key and value. First api is very safe, but you need to be very careful when using second api.

Internally in the View.java Android maintains a static hashmap mapping view to a sparse array. The key and value passed in the settag is stored on the sparse array. There are two important things need to be considered.

First don't save value object having any reference to the activity. This would result in a memory leak as activity will have strong reference from the value and value has a strong reference from the static hashmap maintained by the View.class.

Second every look up for gettag internally have to lookup a hashmap and a sparse array. Which is not very efficient.

Thanks Suriya.


Take care to avoid situations such as:

  • the View is being recycled and thus the existing contents of the tag probably don't suit the new use-case for the view.

  • that some library or other mechanism is using the tag as a "trick" that is not sociable with your use of it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜