Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use integer resources within string resources in android

How can I use some integer that I have stored in my integers.xml file in my strings.xml file.

For example:

I have <integer name="some_integer">5</integer> and I would like to use this in my strings.xml file:

<string name="some_string">This is my string num @integers/some_integer in a row</string>

Apparently my way is not good enough so I need a little help please. I belive there is a possible solutions I just don't know the right one.

Appreciate all the help!

like image 471
slorangex Avatar asked Jul 14 '15 13:07

slorangex


People also ask

Can integers be stored as resources in xml?

An integer defined in XML. Note: An integer is a simple resource that is referenced using the value provided in the name attribute (not the name of the XML file). As such, you can combine integer resources with other simple resources in the one XML file, under one <resources> element. The filename is arbitrary.

Why should you use string resources instead of hardcoded strings in your apps?

As a general rule, you should never use hardcoded strings in your layout but always use string resources (which means the all strings are stored in one separate file where they are easily changeable for different languages and so on).

What is a type of resource for providing your app with strings?

There are three types of resources that can provide your application with strings: String. XML resource that provides a single string. String Array.

Why do we store strings as resources in xml?

The purpose of strings. xml (and other *. xml resource files) is to regroup similar values in one place. This facilitates finding values that would be otherwise buried in the code.


2 Answers

short version is that you can't mix resources like this, but you can use in Java:

getResources.getString(R.string.some_string,
                       getResources.getInteger(R.integer.some_integer)
                      );

and then in your String XML

<string name="some_string">This is my string num %d in a row</string>

that way the %d get replaced by the integer you pass in the getString

like image 132
Budius Avatar answered Sep 17 '22 06:09

Budius


Others said your approach do not work. This is an old answer to face similar problem:

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

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

See this references:

  • http://sagittech.blogspot.com/2012/02/how-to-use-variables-in-android.html

  • http://mobile.tutsplus.com/tutorials/android/android-sdk-format-strings/

like image 34
Roberto Tellez Ibarra Avatar answered Sep 20 '22 06:09

Roberto Tellez Ibarra