Android Development

Reuse string resource in strings.xml

Ok, bad title, cause that is not possible. But it was the goal I wanted to achieve and there are some solutions for it. In Android development the strings.xml file is used to store all Strings in, so you can add support for multiple languages or at least have one place where you can change all your text.

In my case I had the following “problem” illustrated in this example.

I reused the same strings.xml in several applications and had to change the application name in both the app_name and disclaimer message. Using vi with something like :%s/Flappy Bird/Floppy Bird/g worked for me, but I wanted a better solution.

Using String formatting

One solution was to use string formatting in strings.xml. By using String formats we only have to change the application name in one place.

But  using string formatting also means you have to change your Java code.

This is a solution which works great if you reuse a lot of strings, like in a text adventure.

But for my goal it was a little bit of an overkill. I am lazy by nature, so I looked further for another solution, cause I didn’t want to change my Java code.

Using XML Entities
In XML/HTML you have several predefined well-known character entities, like &lt; and &gt; to display a < or > character. But it is also possible to declare new entities in your XML file. This case you don’t have to change your Java code and only make a couple of changes to your XML file.

Now I can reuse my strings.xml in other projects and simply change the defined entities.