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

Java 如何将变量放入字符串资源中?,java,android,Java,Android,是否可以将变量放入字符串资源中?如果是,我如何使用它们 我需要的是: 下一个%X结果 并在%X处加一个int。你射中了%1$d磅的肉! <string name="meatShootingMessage">You shot %1$d pounds of meat!</string> int numPoundsMeat = 123; String strMeatFormat = getResources().getString(R.string.meatShooti

是否可以将变量放入字符串资源中?如果是,我如何使用它们

我需要的是:

下一个%X结果

并在%X处加一个int。

你射中了%1$d磅的肉!
<string name="meatShootingMessage">You shot %1$d pounds of meat!</string>  


int numPoundsMeat = 123;
String strMeatFormat = getResources().getString(R.string.meatShootingMessage, numPoundsMeat);
int numPoundsMeat=123; String strmatformat=getResources().getString(R.String.meatShootingMessage,numPoundsMeat);
示例取自

是的,您可以使用。 将标签添加到string.xml文件中,然后在.java文件中重新发送标签后,您可以按照以下步骤操作

安德里奥达普


String str=getResources().getString(R.String.name)

只需将其作为formatArgs对象传递给getString()函数即可

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

下一个%1$d个结果
你射中了%1$d磅肉!将第二个变量字符串放在这里%2$s,将第三个变量整数放在这里%3$d
int intVariable1=123;
String stringVariable2=“您的字符串”;
int intVariable3=456;
String strmatformat=getResources().getString(R.String.message,intVariable1,stringVariable2,intvariable3);

FYI,Resources.getString(int-resId,Object…formatArgs)是另一种类似于String.format()的方法,它接受资源id和对象参数。允许您跳过最后一步。标志文档:您是如何在
stringVariable2
中将字符串值分配给int的?@salman通过使用%2$s,我已将字符串值分配给第二位的字符串,而不是int
<string name="next_x_results">Next %1$d results</string>
<string name="message">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.message, intVariable1, stringVariable2 , intVaribale3);