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

Guy*_*kes 58 java android

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

我需要的是以下内容:

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

并用int代替%X.

Yas*_*yar 95

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


int numPoundsMeat = 123;
String strMeatFormat = getResources().getString(R.string.meatShootingMessage, numPoundsMeat);
Run Code Online (Sandbox Code Playgroud)

这里取的例子

  • FYI,Resources.getString(int resId,Object ... formatArgs)是另一种类似于String.format()的方法,它接受资源id和Object参数.让您跳过最后一步. (35认同)
  • 标志的文档:http://developer.android.com/reference/java/util/Formatter.html (10认同)

Roe*_*oel 34

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

int nextResultsSize = getNextResultsSize();
String strNextResultsSize = 
     getResources().getString(R.string.next_x_results, nextResultsSize);
Run Code Online (Sandbox Code Playgroud)

XML:

<string name="next_x_results">Next %1$d results</string>
Run Code Online (Sandbox Code Playgroud)


Atu*_*waj 9

<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);
Run Code Online (Sandbox Code Playgroud)

  • 你是如何为 `stringVariable2` 中的 int 分配字符串值的? (2认同)