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

转自王世辉博客

个人资料

原创
342
粉丝
259
喜欢
12
评论
102
等级:
访问:
73万+
积分:
1万+
排名:
1987
勋章:

转自: https://blog.csdn.net/wangshihui512/article/details/50850793


项目中有时候需要为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>

https://blog.csdn.net/wangshihui512/article/details/50850793
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值