为什么这个方法会编译?
private int test(){
return R.string.test;
}
R.string.test
在我的android strings.xml
文件中以这种方式定义:
<resources>
<string name="test">Test</string>
</resources>
我所知道的关于逻辑,宇宙和生命本身的一切目前都没有意义。请帮助一个迷茫的灵魂。
答案 0 :(得分:2)
当您定义资源时,android代码生成器会读取resources
文件并生成一个包含所有R.java
的java文件resources id
,这就是为什么代码编译正确的原因。
答案 1 :(得分:1)
R.string.teste
将字符串的id作为整数。所以我没有看到任何问题...
要获取字符串,您应该写context.getResources().getString(R.string.teste)
答案 2 :(得分:1)
试试这个:
private String test(){
String mess = getResources().getString(R.string.test);
return mess;
}
答案 3 :(得分:1)
在Android中,位于res
文件夹中的所有资源都在名为R.java
的类中编译,在那里,您拥有所创建资源的标识符。例如,在R.java
类的内部,有一个名为string
的子类用于字符串,id
用于ID,依此类推。在您的示例中,您将拥有:
public final class R {
// Other stuff
public static final class string {
public static final int test=0x7f05001c;
// More String resources
}
// Other stuff
}
因此,当您执行return R.string.test;
时,您将返回该资源的ID,在我的示例中0x7f05001c
如果你想要的是检索字符串本身,而不是它的id,你需要做@Suvitruf告诉你的事情:context.getResources().getString(R.string.test)