Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put variable inside string-resources?

Tags:

java

android

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.

like image 623
GuyFawkes Avatar asked May 02 '11 07:05

GuyFawkes


People also ask

How do you store variables in a string?

Here are some more examples of storing strings into variables: string lastName = "Smith"; string book = "Second Foundation"; string foo = "blah"; It is important to note that the variable name can be anything you want as long as it does not contain any spaces.

How do I add a variable to a string in xml?

If you need two variables in the XML , you can use: %1$d text... %2$d or %1$s text... %2$s for string variables.

How do you use string resources in Java?

android:text="@string/hello" /> String string = getString (R. string. hello); You can use either getString(int) or getText(int) to retrieve a string.


2 Answers

<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

like image 160
Yasin Bahtiyar Avatar answered Oct 03 '22 11:10

Yasin Bahtiyar


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> 
like image 22
Roel Avatar answered Oct 03 '22 11:10

Roel