Android中通過Tag為View儲存資料繫結資料
阿新 • • 發佈:2019-01-27
專案中有時候需要為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的原始碼:
/**可以為View繫結key-value資料,但是key不能隨便取值,必須取資原始檔中資源id,保證id的唯一* 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); }
如可在string.xml中設定兩個常量
<item name="tag_id" type="id"></item> <item name="tag_type" type="id"></item>