java 当我需要一个字符串时,R.string.XXX 从strings.xml 返回一个int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16364334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
R.string.XXX returns an int from strings.xml when I need a String
提问by Matt
This is sort of a continuation of this thread:
这是这个线程的延续:
Localizing strings in strings.xml gives NullPointerException
在 strings.xml 中本地化字符串会产生 NullPointerException
This issue arose after going through and implementing the solution provided in that thread. The solution provided worked for instances like this:
在完成并实施该线程中提供的解决方案后,出现了此问题。提供的解决方案适用于这样的实例:
loading = (TextView)findViewById(R.id.loading);
loading.setText(R.string.loading);
This does not work for situations like below:
这不适用于以下情况:
exodus.add(new Question(R.string.a, R.string.b, R.string.c, R.string.d, 0, R.string.e, -1, R.string.f));
The error is The constructor Question(int, int, int, int, int, int, int, int) is undefined
. The contructor for Question is supposed to be Question(String, String, String, String, int, String, int, String)
but these:
错误是The constructor Question(int, int, int, int, int, int, int, int) is undefined
。Question 的构造函数应该是Question(String, String, String, String, int, String, int, String)
这些:
R.string.X
are returning as ints instead of Strings.
返回为整数而不是字符串。
What can I do to fix this problem? And also, if you know, why is this method working for setting text of TextView
s but not parameters in objects?
我能做些什么来解决这个问题?而且,如果您知道,为什么此方法适用于设置TextView
s 的文本而不适用于对象中的参数?
回答by Raghav Sood
R.string.*
is a reference to an int in R.java that points to your actual String.
R.string.*
是对 R.java 中 int 的引用,它指向您的实际字符串。
Use context.getResources().getString(R.string.*);
to get the actual String value.
使用context.getResources().getString(R.string.*);
以获得实际的字符串值。
回答by Voicu
For your last question:
对于您的最后一个问题:
You are using the setTextmethod prototype which takes a resid argument, not a String
, that's why it's working. R.string.loading
returns an int
representing that resid. Had you been calling the setText
method with the getString(R.string.loading)
argument, then it would have used the setTextprototype.
您正在使用setText方法原型,它采用一个 resid 参数,而不是 a String
,这就是它起作用的原因。R.string.loading
返回一个int
代表该居住地。如果您setText
使用getString(R.string.loading)
参数调用该方法,那么它将使用setText原型。
回答by MDMalik
Please refer to this StackOverFlow Question
请参考这个 StackOverFlow 问题
String mystring = getResources().getString(R.string.mystring);