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 分配给视图的标签?

4

2 回答 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)
    )
 );

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

于 2013-05-27T20:19:50.857 回答
1

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);
于 2012-11-16T20:39:11.013 回答