Páginas

Parameters in strings

When we get string from string.xml file, we can use some advanzed options, including using parameters.

For example, if we want to show a business data, like username. A simple solution is to concatenate it with a string from xml file:

getString(R.string.hello) + Model.user_name;

This is a correct solution, but not enough if we want to insert the value in the middle of the chain. In this case we can use the possibility to add parameters. We need an entry like this in the file string.xml.


<string name="hello">Hello %1$s, wellcome</string>

Each parameter has one digit that is used as a sequential identifier, and another one to tell the type: s - string, d - decimal...

In our code, we can complete the string with the next line.

String.format(getString(R.string.hello), Model.user_name);

Format method on class String can receive as many parameters as needed, so we can add all we need.

No hay comentarios:

Publicar un comentario