Android XML: Set Resource id as View's tag in XML layout file

androidnotgenius picture androidnotgenius · Aug 3, 2012 · Viewed 10.2k times · Source

I want to specify a relationship between two views in my Android XML layout file. Here is what I want to do:

 <View
      android:id="@+id/pathview"
      android:layout_width="match_parent"
      android:layout_height="match_parent" />
  ...
  <CheckBox
      android:id="@+id/viewPath"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:checked="true"
      android:paddingRight="7dp"
      android:shadowColor="#000000"
      android:shadowDx="0.5"
      android:shadowDy="0.5"
      android:shadowRadius="0.5"
      android:tag="@id/pathview"
      android:text="Paths" />

However, the XML parser is treating the tag as a String and not interpreting it as an integer (System.out.println((String) [viewPath].getTag()); prints "false"). Is there any way I can assign the resource id to the View's tag?

Answer

32bits picture 32bits · May 27, 2013

If you use

android:tag="?id/pathview" 

you will get a string id as a decimal integer prefixed with a question mark. I'm not able to find documentation for this behavior but it seems stable enough. What you are doing is requesting the id for the current theme. Why the resulting string is then prefixed with a '?' is unknown.

For example:

Given some identifier,

public static final int test_id=0x7f080012;

doing,

android:tag="?id/test_id"

will result in a tag value:

"?2131230738"

You can then do:

 View otherView = activity.findViewById(
    Integer.parseInt(
        someView.getTag().toString().substring(1)
    )
 );

Of course you'll want to check the tag for null and catch NumberFormatException if you are writing more generalized logic.