How to set integer tag to a widget in xml layout file?

后端 未结 4 527
天命终不由人
天命终不由人 2021-01-07 17:45

I have simple layout, but I can only set string tag. How to set integer tag?



        
相关标签:
4条回答
  • 2021-01-07 18:31

    I used the following to setup the tag in xml and handle it later in code:

    <?xml version="1.0" encoding="UTF-8"?>
    <resources>
    <string name="item_tag">1</string>
    </resources>
    
    <!-- TextView with Tag -->
    <TextView
    android:id="@+id/item_with_tag"
    android:tag="@string/item_tag"/>
    
    // retrieve the tag
    int itemTag = Integer.valueOf((String) textView.getTag()); // itemTag == 1
    
    0 讨论(0)
  • 2021-01-07 18:32

    In xml you can only set String. But in code you can use View.setTag(int value); because it takes Object. To read a value you need to cast it to Integer int value = (Integer)view.getTag();

    0 讨论(0)
  • 2021-01-07 18:37

    From the author's edit I attempted to use @integer/int2 to set the tag as an integer, but it still seems that getTag() is returning the tag as a String (at least in Jellybean). Integer.parseInt(String) can convert a String to an Integer and @integer/int2 can validate that your tag is a proper Integer. So if you want to put an Integer in a tag through XML that is probably the best route. Downside, since it uses parseInt it likely takes a little more time than having it stored as a int the whole time.

    0 讨论(0)
  • 2021-01-07 18:39

    Supply a tag for this view containing a String, to be retrieved later with View.getTag() or searched for with View.findViewWithTag().

    Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character.

    For more information go to android:tag

    0 讨论(0)
提交回复
热议问题