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

10,242

Solution 1

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.

Solution 2

You can set the id string as a tag and then get the id.

some like:

<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="pathview"
  android:text="Paths" />

Then in your code:

CheckBox viewPath = findViewById(R.id.pathview);
String pathViewStrId = (String) viewPath.getTag();
int patViewId = getResources().getIdentifier(pathViewStrId, "id", getPackageName());
View pathView = findViewById(patViewId);
Share:
10,242
androidnotgenius
Author by

androidnotgenius

Updated on July 13, 2022

Comments

  • androidnotgenius
    androidnotgenius almost 2 years

    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?

  • NameSpace
    NameSpace almost 10 years
    great answer! used this to embed default resource id's for image button drawables, so they could be determined programatically.