Android Programmer : How to use placeholders in an Android String resource

Imagine you want to have in your strings.xml the copy for a precomposed tweet. In the end you want something like this:

“Groovy Calamari ( by @sdelamo is the best newsletter in the world.”

However, you don’t want the newsletter name, url and author twitter username to be hardcoded.

Fortunately we can use placeholders. Move the values to constants:

static final String NEWSLETTER_NAME = "Groovy Calamari";
static final String NEWSLETTER_URL = "";
static final String NEWSLETTER_AUTHOR = "@sdelamo";

Add to strings.xml the text:

%1$s (%2$s) by %3$s is the best newsletter in the world

Then you can just call it with:

String message = getApplicationContext().getString(R.string.share_text, NEWSLETTER_NAME, NEWSLETTER_URL, NEWSLETTER_AUTHOR);

Leave a Reply

Your email address will not be published. Required fields are marked *