如何将变量放入字符串资源?

时间:2011-05-02 07:42:36

标签: java android

是否可以将变量放在字符串资源中?如果是的话 - 我该如何使用它们。

我需要的是以下内容:

<string name="next_x_results">Next %X results</string>

并用int代替%X。

4 个答案:

答案 0 :(得分:91)

<string name="meatShootingMessage">You shot %1$d pounds of meat!</string>  


int numPoundsMeat = 123;
String strMeatFormat = getResources().getString(R.string.meatShootingMessage, numPoundsMeat);

取自here

的示例

答案 1 :(得分:34)

只需将它作为formatArgs Object传递给getString()函数。

int nextResultsSize = getNextResultsSize();
String strNextResultsSize = 
     getResources().getString(R.string.next_x_results, nextResultsSize);

XML:

<string name="next_x_results">Next %1$d results</string>

答案 2 :(得分:7)

<string name="meatShootingMessage">You shot %1$d pounds of meat! Put Second Variable String here %2$s and third variable integer here %3$d</string>
int intVariable1 = 123;
String stringVariable2 = "your String";
int intVariable3 = 456;
String strMeatFormat = getResources().getString(R.string.meatShootingMessage, intVariable1, stringVariable2 , intVaribale3);

答案 3 :(得分:-2)

是的,你可以使用。 将标签添加到string.xml文件然后在.java文件中重新启动它后,您可以按照此操作。

AndriodApp

String str = getResources()。getString(R.string.name);

相关问题