[英]Why does this method compile?
Why does this method compile? 为什么要编译此方法?
private int test(){
return R.string.test;
}
R.string.test
is defined this way in my android strings.xml
file: R.string.test
是在我的android strings.xml
文件中以这种方式定义的:
<resources>
<string name="test">Test</string>
</resources>
Everything I know about logic, the universe and life itself currently makes no sense. 我所知道的关于逻辑,宇宙和生命本身的一切目前都毫无意义。 Please help a confused soul.
请帮助一个困惑的灵魂。
定义资源时,Android代码生成器将读取resources
文件并生成具有所有resources id
的Java文件R.java
,这就是代码正确编译的原因。
R.string.teste
get id of string as integer. R.string.teste
以整数R.string.teste
获取字符串的id。 So i didn't see any problems... 所以我没看到任何问题...
To get string you should write context.getResources().getString(R.string.teste)
要获取字符串,您应该编写
context.getResources().getString(R.string.teste)
Try this : 尝试这个 :
private String test(){
String mess = getResources().getString(R.string.test);
return mess;
}
In Android, all the resources located in the res
folder are compiled in a class called R.java
, there, you have an identifier of the resource created. 在Android中,位于
res
文件夹中的所有资源都在一个名为R.java
的类中进行编译,在那里,您具有创建的资源的标识符。 For example, inside of the R.java
class there is a sub class called string
for the Strings, id
for the ids and so on. 例如,在
R.java
类的内部,有一个名为string
的子类(用于Strings),一个id
用于ids)等等。 In your example you will have: 在您的示例中,您将具有:
public final class R {
// Other stuff
public static final class string {
public static final int test=0x7f05001c;
// More String resources
}
// Other stuff
}
So when you are doing return R.string.test;
所以当你做的时候
return R.string.test;
you are returning the id for that resource, in my example 0x7f05001c
您正在返回该资源的ID,在我的示例中为
0x7f05001c
If what you want is retrieve the string itself, instead of its id, you need to do what @Suvitruf told you: context.getResources().getString(R.string.test)
如果要检索的是字符串本身而不是ID,则需要执行@Suvitruf告诉您的操作:
context.getResources().getString(R.string.test)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.