Android XML:在XML布局文件中将资源ID设置为视图的标签

3

我想在我的Android XML布局文件中指定两个视图之间的关系。这是我想做的:

 <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" />

然而,XML解析器将标签视为字符串,而不是将其解释为整数(System.out.println((String) [viewPath].getTag()); 输出“false”)。有没有办法将资源ID分配给View的标签?


1
https://dev59.com/J1TTa4cB1Zd3GeqPuKA7 - Georgy Gobozov
2个回答

2
如果您使用
android:tag="?id/pathview" 

你会得到一个以问号为前缀的十进制整数字符串id。我无法找到这种行为的文档,但它似乎相当稳定。你所做的是请求当前主题的id。为什么结果字符串以'?'为前缀是未知的。
例如:
给出一些标识符,
public static final int test_id=0x7f080012;

正在进行中,

android:tag="?id/test_id"

会导致标签的值:
"?2131230738"

今日免费次数已满, 请开通会员/明日再来
 View otherView = activity.findViewById(
    Integer.parseInt(
        someView.getTag().toString().substring(1)
    )
 );

当然,如果您正在编写更通用的逻辑,则需要检查标记是否为空并捕获NumberFormatException。

很棒的答案!我用它来嵌入图像按钮可绘制的默认资源ID,以便可以在程序中确定。 - NameSpace

1

您可以将ID字符串设置为标签,然后获取该ID。

例如:

<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" />

然后在你的代码中:

CheckBox viewPath = findViewById(R.id.pathview);
String pathViewStrId = (String) viewPath.getTag();
int patViewId = getResources().getIdentifier(pathViewStrId, "id", getPackageName());
View pathView = findViewById(patViewId);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接