Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

android - Eclipse/Java - Values in R.string.* return int?

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);

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...