Tag方法
void setTag(Object tag)
這個方法相對簡單讨便,如果只需要設(shè)置一個 tag,那么直接調(diào)用 setTag(Object tag) 取值:view.getTag();方法就可以輕松搞定
void setTag (int key, Object tag)
“ The specified key should be an id declared in the resources of the application to ensure it is unique (see the ID resource type). Keys identified as belonging to the Android framework or not associated with any package will cause an IllegalArgumentExceptionto be thrown.”
IllegalArgumentException 的原因就在于 key 不唯一以政,那么如何保證這種唯一性呢?
我使用了private static final int TAG_ONLINE_ID = 1;
用來當(dāng)做 Key 可是還是會報錯霸褒。但這是為什么呢?
/**
* Returns the tag associated with this view and the specified key.
*
* @param key The key identifying the tag
*
* @return the Object stored in this view as a tag
*
* @see# setTag(int, Object)
* @see# getTag()
*/
public Object getTag(int key) {
if (mKeyedTags != null) return mKeyedTags.get(key);
return null;
}
/**
* 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);
}
從源碼中可以看到盈蛮,key右移24位如果小于2就會拋出這個異常废菱,這個應(yīng)該和id的生成規(guī)則有關(guān)。
這樣來看key也是可以定義成一個常量的(測試了也確實(shí)可以)抖誉,只要保證這個移位大于2的規(guī)則就行殊轴。但是這樣寫不便于維護(hù),只是說是可行的袒炉,不建議這邊做旁理。
從源碼中注意到的另外一個問題是,setTag()中的tag是單獨(dú)存儲的我磁,保存在protected Object mTag;中孽文,而setTag(int key, final Object tag)的tags是保存在private SparseArray<Object> mKeyedTags;中的。
那么知道問題就好解決了:
最直接的方法就是在資源文件中添加一條記錄:
<item type="id" name="tag_first"></item>
可以添加到res/values/strings.xml或者res/values/ids.xml中夺艰,然后調(diào)用View.setTag(R.id.tag_first,"msg")即可芋哭。