Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 939
Lukap Avatar asked May 02 '12 10:05

Lukap


4 Answers

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.

like image 177
Savelii Zagurskii Avatar answered Oct 21 '22 13:10

Savelii Zagurskii


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.

like image 27
Dharmendra Avatar answered Oct 21 '22 14:10

Dharmendra


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

like image 16
Lalit Poptani Avatar answered Oct 21 '22 12:10

Lalit Poptani


You can concatenate the resources in gradle.build:

    resValue "string", "TWITTER_CALLBACK", "twitter_callback_" + applicationId
like image 9
Boy Avatar answered Oct 21 '22 12:10

Boy