为什么 .getIdentifier() 从 class 中检索一个数字?
Why .getIdentifier() retreive a number from class?
当我尝试从 activity 获取字符串时,"getIdentifier" 工作正常:
Toast.makeText(this, getResources().getIdentifier("frase", "string", getPackageName()), Toast.LENGTH_SHORT).show();
但是当从非 activity class 尝试时,它会检索到一个数字(例如:2131099793):
getContext().getResources().getIdentifier("frase" , "string", getContext().getPackageName();
为什么会这样?
getIdentifier()
returns 和 int
,如您在 the JavaDocs 中所见。那int
就是资源的标识符。在您的情况下,int
与 R.string.frase
相同。
在您的第一个代码片段中,您将该资源标识符传递给 Toast.makeText()
。 makeText()
假设如果你传递一个 int
,int
是一个字符串资源标识符,所以它会查找字符串资源并使用它。
在您的第二个代码片段中,您只是使用了 int
。使用 getString()
将 int
资源标识符转换为当前配置的相应字符串。
当我尝试从 activity 获取字符串时,"getIdentifier" 工作正常:
Toast.makeText(this, getResources().getIdentifier("frase", "string", getPackageName()), Toast.LENGTH_SHORT).show();
但是当从非 activity class 尝试时,它会检索到一个数字(例如:2131099793):
getContext().getResources().getIdentifier("frase" , "string", getContext().getPackageName();
为什么会这样?
getIdentifier()
returns 和 int
,如您在 the JavaDocs 中所见。那int
就是资源的标识符。在您的情况下,int
与 R.string.frase
相同。
在您的第一个代码片段中,您将该资源标识符传递给 Toast.makeText()
。 makeText()
假设如果你传递一个 int
,int
是一个字符串资源标识符,所以它会查找字符串资源并使用它。
在您的第二个代码片段中,您只是使用了 int
。使用 getString()
将 int
资源标识符转换为当前配置的相应字符串。