Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate multiple strings in android XML? [duplicate]

Problem
I would like to be able to do something like that in Android XML code:

<string name="title">@string/app_name test</string> <string name="title2">@string/app_name @string/version_name</string> 

Regarding first line of code compiler shows this error

No resource found that matches the given name (at 'title' with value '@string/app_name test')

and regarding second line of code compiler shows this error

No resource found that matches the given name (at 'title2' with value '@string/app_name @string/version_name')

Question
Does anybody know how to concatenate multiple strings in Android XML?

Rationale
It is bad practice to duplicate variable values in many places of code (in this case XML).

like image 642
Andrzej Duś Avatar asked Apr 23 '11 13:04

Andrzej Duś


People also ask

How do I concatenate multiple strings?

Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.

Can you concatenate more than 2 strings?

Example: Concatenation of strings in columns Note how a nested function is used as the second argument. This is one way to concatenate multiple strings when you have more than two values that you want to use as arguments.

What is the most efficient way to concatenate many strings together?

If you are concatenating a list of strings, then the preferred way is to use join() as it accepts a list of strings and concatenates them and is most readable in this case. If you are looking for performance, append/join is marginally faster there if you are using extremely long strings.


1 Answers

I've tried to do a similar maneuver myself but I was told this is not doable in Android.

The interesting thing is that you get an error message that indicates that it indeed is possible but due to errors in resource matching it's not possible right now. (Are you sure you have defined the "app_name" and "version_name" strings before the "title" and "title2" strings?)

You can however do something like:

<string name="title">%1$s test</string> <string name="title2">%1$s %2$s</string>  <string name="app_name">AppName</string> <string name="version_name">1.2</string> 

And then from Java code do something like:

Resources res = getResources(); String appName = res.getString(R.string.app_name); String versionName = res.getString(R.string.version_name);  String title = res.getString(R.string.title, appName); String title2 = res.getString(R.string.title2, appName, versionName); 

More about formatting strings in Android.

Hope this helps.

like image 106
dbm Avatar answered Sep 17 '22 21:09

dbm