Resources.getIdentifier()有异常行为时的名字是数字 [英] Resources.getIdentifier() has unexpected behavior when name is numeric

查看:98
本文介绍了Resources.getIdentifier()有异常行为时的名字是数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用Resources.getIdentifier动态加载字符串资源;因为我动态传递需要从我的资源文件翻译的串。它返回0,当资源不存在;所以我搞定。然而,当我传递一个字符串,它是一个数字;尽管我没有在我的资源定义,它返回我通过了,而不是0。这在数量上会导致系统崩溃,当我试图获取资源。

I use Resources.getIdentifier to load up string resources dynamically; because I am dynamically passed a string that needs to be translated from my resources files. It returns 0 when the resource doesn't exist; so I handle that. However, when I pass in a string that is a numeric; even though I don't have that defined in my resources, it returns the number I passed in instead of 0. This causes a crash when I try to get that resource.

int identifier = context.getResources().getIdentifier(myText, "string", "com.farragut.android.emsspeak");
if (identifier > 0) {
    text2.setVisibility(View.VISIBLE);
    text2.setText(context.getResources().getString(identifier));
} else {
    text2.setVisibility(View.GONE);
}

这是定义的行为?我想不通为什么它工作正常会将myText时的嗒嗒但随后会将myText时是12是不同的。我唯一​​能想到的就是测试会将myText是否是数字第一;虽然我能找到这样做的唯一办法就是尝试分析它作为一个整数,赶上一个NumberFormatException异常。那是最好的解决办法?

Is this defined behavior?? I can't imagine why it works fine when myText is "BLAH" but then when myText is "12" it is different. The only thing I can think of is to test if myText is numeric first; though the only way I can find to do that is to try to parse it as an integer and catch a numberFormatException. Is that the best solution?

推荐答案

嗯,这是有点儿奇怪,但如果我指定像它提到的则getIdentifier()文档,它工作正常,否则的全名我得到了相同的结果就像你

Well this is kinda weird but if I specify the fully qualified name like it's mentioned in the getIdentifier() documentation it works properly otherwise i got the same result like you.

则getIdentifier试用(com.farragut.android.emsspeak:字符串/会将myText +,NULL,NULL);

这篇关于Resources.getIdentifier()有异常行为时的名字是数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆