Concatenate multiple strings in XML?
I go through this How to concatenate multiple strings in android XML? and in the end there are comments that
For clarity, Its works:
<string name="title">@string/app_name</string>.
– Andrzej Duś
I made my own example but it doesn't works. So does Andrzej wrong or I am doing something wrong in my code.
R.strings.bbb
should contains "bbb aaa"
but instead of "bbb aaa"
it contains "bbb @strings/aaa"
<string name="aaa">aaa</string>
<string name="bbb">bbb @strings/aaa</string>
Query:
Is it possible to do some concatenation only in xml, without source code changes?
Reason why I don't want to edit in code because I use this strings in xml/preferences.xml
For Example:
<ListPreference android:key="key_bbb" android:title="@string/bbb"
....
If you know what I mean, here there is no possibility to use something like this
String title = res.getString(R.string.title, appName);
Solution 1:
No, you can't concatenate strings in XML but you can define XML resources.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE resources [
<!ENTITY appname "MyAppName">
<!ENTITY author "MrGreen">
]>
<resources>
<string name="app_name">&appname;</string>
<string name="description">The &appname; app was created by &author;</string>
</resources>
The original answer was posted here.
Solution 2:
In XML only this is not possible but using the java code you can use the String.format()
method.
<string name="aaa">aaa</string>
<string name="bbb">bbb %1$s</string>
In java code
String format = res.getString(R.string.bbb);
String title = String.format(format, res.getString(R.string.aaa));
So title will be a full string after concatenation of two strings.
Solution 3:
No I don't think you can concatenate.
<string name="aaa">aaa</string>
<string name="bbb">bbb @string/aaa</string>
Output - bbb @string/aaa
If you do,
<string name="aaa">aaa</string>
<string name="bbb">@string/aaa bbb</string> -> This won't work it
will give compilation error
Because here it will search for a String with reference @string/aaa bbb
which does not exists.
Problem in your case was, you where using @strings/aaa
which should be @string/aaa
Solution 4:
You can concatenate the resources in gradle.build:
resValue "string", "TWITTER_CALLBACK", "twitter_callback_" + applicationId
Solution 5:
Yes, you can do it if your XML files are using DataBinding as you can see in this link
Use it like this:
"@{@string/first_string+ @string/second_string}"