Somewhere I read how to use variables in XML document. They said it's very simple and I guess it was. I successfully used it that way in Android strings.xml file. I was using it that way the whole day until suddenly android stopped to parse it and stopped to treat it like a variable.
I used it in this way:
<resources>
<string name="some_string">string1</string>
<string name="another_string"> {$some_string} trolololo </string>
</resources>
and in java accessing it through: getApplicationContext().getString(R.strings.another_string);
getApplicationContext().getString(R.strings.another_string);
In the output I used to receive string like:
string1 trolololo
and now I receive only:
{$some_string} trolololo
Does anyone have any idea what is wrong? I know that Android's XML may differ than standard XML, but IT USED TO WORK. Awww... Thanks for any advice.
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.
String. xml file contains all the strings which will be used frequently in Android project. String. xml file present in the values folder which is sub folder of res folder in project structure.In Android Studio, we have many Views such as TextView,Button,EditText,CheckBox,RadioButton etc.
Assuming that you want to pass a string value as a parameter in the another_string
then your string is not well formatted to receive that argument and if you try to use it your output will be {$some_string} trolololo
.
If you need to format your strings using String.format(String, Object...), then you can do so by putting your format arguments in the string resource.
<resources>
<string name="some_string">string1</string>
<string name="another_string">%1$s trolololo</string>
</resources>
Now your able to format the string with arguments from your application like this:
String arg = "It works!";
String testString = String.format(getResources().getString(R.string.another_string), arg);
Log.i("ARG", "another_string = " + testString);
Doing so the output string will be another_string = It works! trolololo
.
Take a look at the Android Developers official documentation, here.
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 the getApplicationContext().getString(R.strings.another_string)
will be string1 trolololo
.
Or, you can directly use getResources().getString(R.string.activity_title, arg)
.
For example
<resources>
<string name="postfix_title">%s Gallery</string>
</resources>
and then simply,
String arg = "Colors";
String title = getResources().getString(R.string.postfix_title, arg);
This will result in title
containing value Colors Gallery
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With