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

2022-08-31 12:44:11

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

我需要的是以下内容:

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

并将一个 int 放在 %X 的位置。


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


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

从这里获取的示例


答案 2

只需将其传递到 getString() 函数作为 formatArgs Object。

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

XML:

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

推荐