Jegadeesan S
Jegadeesan S

Reputation: 69

How to add many values in android:tag

In Android XML, I want to add multiple values in android:tag. I found one way that we can use multiple for adding values.

<TextView   
         android:id="@+id/myTextView"   
         android:layout_width="wrap_content"   
         android:layout_height="wrap_content">
        <tag android:id="@+id/value_one" android:value="@string/value_one"/>
        <tag android:id="@+id/value_two" android:value="@string/value_two"/>
        <tag android:id="@+id/value_three" android:value="@string/value_three"/>
 </TextView>

But this method work only in API level 21 and above. The Android provides the following error while using above method.

tag is only used in API level 21 and higher (current min is 19)

In API level 19, we have an option to set tag in programmatically. Is there any other option to add multiple strings or Object in XML itself?

Upvotes: 2

Views: 840

Answers (1)

Java42
Java42

Reputation: 657

The trick to set multiple values inside android:tag="" does not lie within android:tag="" because you can always set multiple tags as in: android:tag="TAG1:TAG2:TAG3". The trick is in finding and parsing the tag in your code. When you are checking for the existence of a particular tag, do something like the following (tweak and add error handling as necessary):

public static boolean isTagDefined(View view, String tag) {
    boolean rc = false;
    Object tags = view.getTag();
    if (tags instanceof String) {
        rc = ((String) tags).contains(tag);
    }
    return rc;
}

Be careful when naming and delimiting tags. If you need key/value pairs, change your tag and parsing technique (StringTokenizer) to handle something like "KEY1_VALUE:KEY2_VALUE". You could also use JSON objects but I believe that would be overkill because the use of view tags is likely to be needed for simple control/debug functions.

Upvotes: 2

Related Questions