为什么我会得到这个例外?

05-18 20:29:38.044: ERROR/AndroidRuntime(5453): java.lang.IllegalArgumentException: The key must be an application-specific resource id.
05-18 20:29:38.044: ERROR/AndroidRuntime(5453):     at android.view.View.setTag(View.java:7704)
05-18 20:29:38.044: ERROR/AndroidRuntime(5453):     at com.mypkg.viewP.inflateRow(viewP.java:518)

所讨论的行是:

((Button) row.findViewById(R.id.btnPickContact)).setTag(TAG_ONLINE_ID,objContact.onlineid);

我将其定义为:

private static final int TAG_ONLINE_ID = 1;
有帮助吗?

解决方案

标签ID必须是唯一的,因此它希望它是在资源文件中创建的ID以保证唯一性。

如果视图仅包含一个标签,尽管您只能执行

setTag(objContact.onlineid);

其他提示

您无法使用settag(int,对象)的原因是因为Android需要“ INT”参数中预编译的唯一ID。

尝试在string.xml xml中创建两个唯一条目,说“ firstName”&“ secondname”并使用下面使用它们

imageView.setTag(R.string.firstname, "Abhishek");
imageView.setTag(R.string.lastname, "Gondalia");

我参加聚会有点迟了,但今天我本人偶然发现了这个问题,并认为我也会给出一个答案。这个答案将是其他答案的汇编,但有所不同。首先,正如其他人指出的那样,ID不能是代码中定义的常数(例如私有静态最终int myid = 123)或您将其定义为某个地方的任何其他INT。

ID必须是预编译的唯一ID,就像您在values/strings.xml(即r.string.mystring)中获得的字符串所获得的ID一样。参考 http://developer.android.com/guide/topics/resources/available-resources.htmlhttp://developer.android.com/guide/topics/resources/more-resources.html 了解更多信息。

我的建议是,您创建一个名为values/tags.xml的新文件,然后写:

    <resources xmlns:android="http://schemas.android.com/apk/res/android">
      <item name="TAG_ONLINE_ID" type="id"/>
    </resources>

我认为最好创建一个单独的文件,而不是按照Etiennesky的建议将其放入strings.xml中。

这将完成工作...

如果您的班级中只有1个SELTAG,则可以使用任何INT,也许在顶部声明的静态最终最终。

当您有2个或更多的Settag带有不同的钥匙键时,问题就来了。我是说:

public static final int KEY_1 = 1;
public static final int KEY_2 = 2;
...
setTag(KEY_1)
setTag(KEY_2)
...

这种情况是错误的。然后,您需要添加一个名为ids.xml的值文件,其中包括以下内容:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item type="id" name="resourceDrawable" />
    <item type="id" name="imageURI" />
</resources>

然后,在您的班上,致电:

 ...
 setTag(R.id.resourceDrawable, KEY_1)
 setTag(R.id.imageURI, KEY_2)
 ...
private static final int TAG_ONLINE_ID = 1 + 2 << 24;

应该管用。更多信息 Ceph3us:

指定的密钥应为应用程序资源中声明的ID,以确保其唯一的键被标识为属于Android框架或与任何软件包没有关联的键将导致违法。

来自来源:

public void setTag(int key, final Object tag) {
    // If the package id is 0x00 or 0x01, it's either an undefined package
    // or a framework id
    if ((key >>> 24) < 2) {
        throw new IllegalArgumentException("The key must be an application-specific "
                + "resource id.");
    }

    setKeyedTag(key, tag);
}

我用过了 viewHolder.itemTitleTextView.getId(). 。但是您也可以在您的资源中声明:<item type="id" name="conversation_thread_id"/>

您要通过ID保存值的原因是,您想在此标签中覆盖多个值,对吗?
这里一个更简单的解决方案:
假设您要将两个值(字符串)保存到此标签中:“ firstName”和“ lastName”。您可以将它们都保存在一个字符串中,并由分号隔开:

v.setTag(firstname + ";" + lastname);

...并通过将它们分成字符串数组来访问它们:

String[] data = v.getTag().toString().split(";");
System.out.println(data[0]) //firstname
System.out.println(data[1]) //lastname

这对我有用:

setTag(0xffffffff,objContact.onlineid);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top