Difference between R.string.xxx and getString(R.string.xxx)?

半腔热情 提交于 2020-01-30 12:03:29

问题


What is the difference between two ways to obtain a string from resources:

setPositiveButton(R.string.some_string);

OR

setPositiveButton((getString(R.string.some_string));

?

In both cases I get the same result.


回答1:


R.string.some_string

is a public final static int that is a fixed ID to a specific String in your R.java file. This is generated automatically.

getString(R.string.some_string)

returns the String referenced by the above by reading the R.java file.

It depends on the implementation of

setPositiveButton(String)

and

setPositiveButton(int)

what difference internally is made, like with error checks.




回答2:


setPositiveButton has multiple overloads that accept different types of arguments.

When calling

setPositiveButton(R.string.some_string);

You are telling your application to set the positive buttons text equal to the string that is referenced by your resource ID "some_string".

Where as

setPositiveButton((getString(R.string.some_string));

You are fetching the String value for "some_string" and then assigning that to your positive button;

They work out to be the same because the 1st method does the "getString(R.string.some_string)" portion for you




回答3:


Another difference is that, with getString you can format your String and translate it. For example, in your strings.xml file you can have:

<string name="message">Hello, %1$s</string>

And in some some translation XML file you can have the same, but in another language:

<string name="message">Hola, %1$s</string>

But the good thing is that when you want to show a message and get it translated, you only have to do this:

String message = getString(R.string.message, "John Doe");

And, in the english version it will be Hello, John Doe. But in the spanish version it will be Hola, John Doe.

Not only will translate it, but format it and will give you more control over your code.



来源:https://stackoverflow.com/questions/9877242/difference-between-r-string-xxx-and-getstringr-string-xxx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!