Eclipse / Java - R.string中的值。* return int? [英] Eclipse/Java - Values in R.string.* return int?

查看:150
本文介绍了Eclipse / Java - R.string中的值。* return int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为我会很优雅,并使用string.xml文件为异常消息之类的内容定义一些常量字符串。在strings.xml中,我点击Add,选择String选项(不是'String Array'),然后给它一个名称和值。我很惊讶地发现这段代码不起作用:

I thought I'd be classy and use the string.xml file to define some constant strings for things like exception messages. In strings.xml I hit Add, chose the "String" option (not 'String Array'), then gave it a name and value. I was surprised to see that this code doesn't work:

throw new Exception(R.string.MyExceptionMessage);

这是失败的,因为R.string.MyExceptionMessage实际上是int类型。我可以通过查看R.java来验证该类型。我缺少什么?

And that fails because R.string.MyExceptionMessage is actually of type int. I can verify that type by looking in R.java. What am I missing?

推荐答案

R 类中的所有内容都是引用,因此它只是定义为 int

Everything in the R class is a reference, hence it's just defined as an int.

如果您的代码在—或者有权访问— Android 上下文,你可以调用 context.getString(R.string.my_exception_message)来获得实际的 String value。

If your code is running within — or has access to — an Android Context, you can call context.getString(R.string.my_exception_message) to get the actual String value.

或者,对于不需要翻译的异常字符串这样的东西,所以不需要严格需要要在Android资源.xml文件中定义,您可以将字符串存储为某种 StringConstants 接口中的常量。这样你可以引用实用程序类中可能无法访问 Context 的字符串。

Or, for things like exception strings that don't require to be translated and so don't strictly need to be defined in an Android resource .xml file, you could store the strings as constants in some sort of StringConstants interface. That way you can refer to the strings from within utility classes that may not have access to the Context.

这篇关于Eclipse / Java - R.string中的值。* return int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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