Android_View.Tag()メソッドの使用

2777 ワード

Tagメソッド
void setTag(Object tag)
この方法は比較的簡単で、tagを1つだけ設定する必要がある場合は、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;をキーとして使っていますが、やはり間違っています.しかし、これはなぜですか?
/**
* 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 ID resource type).
* 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未満になるとこの異常が放出され、これはidの生成規則に関係するはずだ.
このようにkeyも定数として定義することができ(テストしても確かに可能である)、このシフトが2より大きい規則を保証すればよい.しかし、このように書くのはメンテナンスに不便で、ただ実行可能だと言って、こちらにはお勧めしません.
ソースコードから気づいたもう一つの問題は、setTag()のtagが単独で格納され、protected Object mTagに保存されることである.で、setTag(int key,final Object tag)のtagsはprivate SparseArray mKeyedTagsに保存されます.に表示されます.
では、問題を知っていれば解決できます.
最も直接的な方法は、リソースファイルにレコードを追加することです.


res/values/strings.xmlまたはres/values/ids.xmlに追加し、View.setTag(R.id.tag_first、msg)を呼び出すことができます.