Android variables in strings.xml

Somewhere I read how to use variables in an XML document. They said it was very simple, and I think it was. I have successfully used it this way in the Android strings.xml file. I used it that way all day, until suddenly the android stopped to parse it, and stopped to consider it as a variable.

I used it as follows:

<resources> <string name="some_string">string1</string> <string name="another_string"> {$some_string} trolololo </string> </resources> 

and in java, through getApplicationContext (). getString (R.strings.another_string);

 getApplicationContext().getString(R.strings.another_string); 

In the output, I used to get a line like:

 string1 trolololo 

and now I only get:

 {$some_string} trolololo 

Does anyone know what is wrong? I know that Android XML may differ from standard XML, but IT IS USED TO WORK. Awww ... Thanks for any advice.

+6
source share
3 answers

This will solve your problem:

 <resources> <string name="some_string">string1</string> <string name="another_string">@string/some_string trolololo</string> </resources> 

Now the output of getApplicationContext().getString(R.strings.another_string) will be string1 trolololo .

+7
source

Assuming you want to pass a string value as a parameter to another_string , then your string will not be well formatted to receive this argument, and if you try to use it, your result will be {$some_string} trolololo .

If you need to format strings using String.format (String, Object ...) , you can do this by putting your format arguments in a String resource.

 <resources> <string name="some_string">string1</string> <string name="another_string">%1$s trolololo</string> </resources> 

Now you can format the string with arguments from your application as follows:

 String arg = "It works!"; String testString = String.format(getResources().getString(R.string.another_string), arg); Log.i("ARG", "another_string = " + testString); 

So the output line will be another_string = It works! trolololo another_string = It works! trolololo .

Take a look at the official Android developers documentation here .

+18
source

I'm not sure how the first initial thing you did worked with curly braces, but I ran into this problem earlier and couldn't find a solution.

Now what I am doing is invoking these lines separately and concatenating them at runtime.

0
source

Source: https://habr.com/ru/post/920626/


All Articles