81

Is it possible to put variables inside string-resources? And if yes - how do i use them.

What i need is the following:

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

and put an int in place of the %X.

Spoike
  • 119,724
  • 44
  • 140
  • 158
GuyFawkes
  • 1,686
  • 3
  • 17
  • 30

4 Answers4

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


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

Example taken from here

MSpeed
  • 8,153
  • 7
  • 49
  • 61
Yasin Bahtiyar
  • 2,357
  • 3
  • 18
  • 18
  • 38
    FYI, Resources.getString(int resId, Object... formatArgs) is another method similar to String.format(), which takes the resource id and the Object arguments. Lets you skip that last step. – Josh May 02 '11 at 17:03
  • 11
    The flags' documentation: http://developer.android.com/reference/java/util/Formatter.html – Brais Gabin Sep 09 '13 at 08:27
36

Just pass it throught getString() function as 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>
Roel
  • 3,089
  • 2
  • 30
  • 34
16
<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);
Atul Bhardwaj
  • 6,647
  • 5
  • 45
  • 63
-3

yes,you can use. after adding tag to string.xml file and then to retrrive the the same in your .java file you can follow this.

AndriodApp

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

krupa parekh
  • 500
  • 3
  • 7