android - 当名称为数字时,Resources.getIdentifier() 具有意外行为

标签 android string parsing resources localization

我使用 Resources.getIdentifier 动态加载字符串资源;因为我动态传递了一个需要从我的资源文件中翻译的字符串。资源不存在时返回0;所以我处理。但是,当我传入一个数字字符串时;即使我没有在我的资源中定义它,它也会返回我传入的数字而不是 0。这会在我尝试获取该资源时导致崩溃。

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 是“BLAH”时它工作正常但是当 myText 是“12”时它是不同的。我唯一能想到的就是首先测试 myText 是否为数字;尽管我能找到的唯一方法是尝试将其解析为整数并捕获 numberFormatException。这是最好的解决方案吗?

最佳答案

这有点奇怪,但如果我像 getIdentifier() 文档中提到的那样指定完全限定名称,它会正常工作,否则我会得到与您相同的结果。

尝试使用 getIdentifier("com.farragut.android.emsspeak:string/"+myText, null, null);

关于android - 当名称为数字时,Resources.getIdentifier() 具有意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6387387/

相关文章:

c - c中的协议(protocol)解析

html - 在 w3c 中验证时出现 CSS 解析错误

c - 如何从字节数组中获取数据

android - 在 Android 中获取 onTouch ACTION_MOVE 事件的速度

用于从用户输入中检索字符串的 c 函数存在内存问题

string - 粘贴前检查剪贴板的内容

python - Python 缩写检测

android - 在AS中预览时消失的面板

java - 如何以编程方式将 XML 可绘制对象设置为背景图像?

android - 不要在 Android 3.x 上获取 Android Market INSTALL_REFERRER