获得从价值的资源ID价值、资源、ID

2023-09-13 00:30:38 作者:三里桃花不及卿

我有很多语言的特定资源。有一个在我的Andr​​oid应用程序在那里我得到的资源价值,需要把这个值转化为匹配id的一个点。的值不一定是在当前语言的语言特定的文件(烯/日/ ......)。这是什么地方在那里...它是独一无二的。

I do have a lot of language specific resources. There's one point in my Android apps where I do get a resource value and need to translate this value into the matching id. The value is not necessarily in the language specific file for the current language (en/de/...). It's somewhere in there ... and it's unique.

阅读文档和这个线程How得到与已知的ressource名称的资源ID?我认为则getIdentifier(字符串名称,字符串DEFTYPE,字符串defPackage)是去正确的方式,但我无法得到它的工作。结果总是0。

After reading the docs and this thread "How to get a resource id with a known ressource name?" I thought that getIdentifier(String name, String defType, String defPackage) is the correct way to go but I can't get it to work. The result is always "0".

这code是一个活动的一部分,我在Android 2.2。

This code is part of an activity and I'm on Android 2.2.

难道Android不只是拿在当前的语言特定的一个所有资源文件考虑在内,并搜索?

Is it possible that Android doesn't take all resource files into account and searches just in the current language specific one?

有关的例子(当前的语言是德):

For an example (current language is "de"):

File: values-en/strings.xml
<resources>
   <string name="txt_afirsttext">A first text</string>
   <string name="txt_asecondtext">A second text</string>
</resources>

File: values-de/strings.xml
<resources>
   <string name="txt_afirsttext">Ein erster Text</string>
   <string name="txt_asecondtext">Ein zweiter Text</string>
</resources>

// Now I want to find the ID to this "en" text ...
String testValue = "A second text";
int i = this.getResources().getIdentifier(testValue, "strings", this.getPackageName());

// ... and translate it to the actual "de" language
String translatedValue = this.getResources().getString(i);

为把事情说清楚。我不想错过使用的字符串资源作为数据库。这是发生在极少数情况下只是其中的一部分。

To make things clear. I don't want to miss-use string resources as a database. It's only one part that occurs on very rare situations.

推荐答案

您正在使用的则getIdentifier 的错误。你不指定文字,但文字的标识,你的情况,这将是的 txt_afirsttext 或 txt_asecondtext 的。

You are using the getIdentifier wrong. You don't specify the text but the identifier of the text, in your case that would be txt_afirsttext or txt_asecondtext.

int i = this.getResources().
             getIdentifier("txt_asecondtext", "string", this.getPackageName());

我觉得没有办法找到其内容的字符串资源标识符。它会像传递一个字节流来定位绘制。

I think there's no way to locate a String resource identifier by its content. It would be like passing a byte stream to locate a drawable.

应用程序是否真的需要这种奇怪的方式获得资源?我敢肯定,你可以用更好的方法来动态加载资源,虽然你的第一段描述您的方案作为一个神秘的一个:)

Does your application really need this weird way of getting resources? I'm quite sure you could use a better approach to dynamically load resources, though your first paragraph describes your scenario as a mysterious one :)

编辑:答案固定。由于tdroza针对校正

edit: Answer fixed. Thanks to tdroza for the correction.