Android中通过Tag为View保存数据绑定数据

项目中有时候需要为View绑定数据,比如每一个云标签都对应服务器一个标签id,View中setTag可以方便的为控件绑定数据。

为控件绑定数据:

selectCategory.setTag(R.id.tag_id, id);
selectCategory.setTag(R.id.tag_type, type);
读取控件绑定的数据:

Object object=selectCategory.getTag(R.id.tag_id);
if(object!=null&& object instanceof Integer){
    ...
setTag的源码:

/**  * Sets a tag associated with this view and a key. A tag can be used  * to mark a view in its hierarchy and does not have to be unique within  * the hierarchy. Tags can also be used to store data within a view  * without resorting to another data structure.  *  * The specified key should be an id declared in the resources of the  * application to ensure it is unique (see the <a  * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).  * Keys identified as belonging to  * the Android framework or not associated with any package will cause  * an {@link IllegalArgumentException} to be thrown.  *  * @param key The key identifying the tag  * @param tag An Object to tag the view with  *  * @throws IllegalArgumentException If they specified key is not valid  *  * @see #setTag(Object)  * @see #getTag(int)  */ public void setTag(int key, final Object tag) {
    // If the package id is 0x00 or 0x01, it's either an undefined package  // or a framework id  if ((key >>> 24) < 2) {
        throw new IllegalArgumentException("The key must be an application-specific "  + "resource id.");
    }

    setKeyedTag(key, tag);
}
可以为View绑定key-value数据,但是key不能随便取值,必须取资源文件中资源id,保证id的唯一

如可在string.xml中设置两个常量

<item name="tag_id" type="id"></item>
<item name="tag_type" type="id"></item>

你可能感兴趣的:(Android中通过Tag为View保存数据绑定数据)