Pages

Wednesday, February 12, 2014

Android Resources

This is not a guide or an article. It is mainly an observation that I can no longer ignorer. The issue is that most Android developers have a habit of working out custom solutions using the few tools that they know, rather than looking to see if Android has a pee-built tool for that specific task.

In this case, the issue is regarding Android's Resources class. Let's say that we want to create a dynamic string using placeholders. If you try to google this, you will mostly find the same solution on each page that you visit. I have written this solution below.

<resources>
    <string name="dynamic_string">Let\'s insert the number %1$d</string>
</resources>

Integer numberToInsert = 1;
String dynamicString = String.format( getResources().getString(R.string.welcome_messages), numberToInsert );

The problem here is that there is no point in including String.format into this, because Resources.getString is already able to do this for you.

Integer numberToInsert = 1;
String dynamicString = getResources().getString(R.string.welcome_messages, numberToInsert );

If you took a look at the documentation for this method, you would see that it does not only take [String] as an argument. It actually takes [String, Object...], where each Object parsed will be used to replace the placeholders of the string.

Please have a look at the Resources Documentation. This class contains a lot of useful tools for when working with the resources in Android. Many of which is not seen being used very much, if even at all.

No comments:

Post a Comment