I have resource strings :
<string name="address">Address</string>
<string name="city">City</string>
<string name="country">Country</string>
<string name="pincode">Pincode</string>
In my application, at few places I am using these strings alone and at few places I am succeeding them by a colon.
I don't what to create another four resource strings :
<string name="address_with_colon">Address: </string>
<string name="city_with_colon">City: </string>
<string name="country_with_colon">Country: </string>
<string name="pincode_with_colon">Pincode: </string>
Now to achieve this, I have to concatenate my resource strings with colon. I know this is very easy though java code which I can write in my activity class. But what I want is to do the concatenation in my layout file.
Question : Is string concatenation possible in layout file?
This is where I have to perform the concatenation:
android:text="concatenation_if_possible"
Nope as far as I know.
One solution is to use what @DIVA has answered before.
Another possible solution is to create a custom view that extends TextView (or the view you want to achieve this) and create a custom attribute
custom:concatenate
which receives a string reference and perform the concatenation automatically. IMHO I think this is the most clean approach.In code will look as this:
Or… you can use the power of Drawables creating a custom TextDrawable (which is explained very well by @Devunwired in this post and the concrete implementation of it in Github).
Copying what @Devunwired has said in his post about it:
This combined with your custom TextView as I explained before (or whatever view you want to use) gives you a very powerful option. Again copying the example that @Devunwired wrote in his post:
If you need more help please let me know in the comments and I'll gladly update the answer!
Using XML entities it's possible to use the same string multiple places within an XML file:
I used this answer: dynamic String using String.xml?
You can so something like this :
No, you cannot concatenate several string resources into a single string when directly referencing those strings from a layout file.
XML layout files are simply a template of instructions for Android to build a user interface, and you should consider them as a cleaner and more organized way to generate your UI than using a Java class that manually creates and positions views in a layout. That being said, there are limitations to what you can do with a layout file, and one of them is being able to reference a single string resource from every view, meaning that you can't do anything more complex than that, including concatenating several strings into one.