Resource Strings Formatting in Android

Problem description

It is a very BAD!! practice to use hardcoded strings in java code, when you can use resources from strings.xml in your application. One of the reasons that you should NOT hardcode any strings (not even a dot) is the localization of your app. A problem arise when you want to localize your app to some strange language like Chinese, Japanese etc.

 

Simple text usage

Wrong

TextView titleView = (TextView) findViewById(R.id.title);
titleView.setText("Profile");

Good

Content of res/values/strings.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="profile_title">Profile</string>
</resources>

 
Code in Activity’s onCreate() method:

titleView.setText(getString(R.string.profile_title));

(getString() method is available from Context as well as from Fragment objects.)
 
Even better

titleView.setText(R.string.profile_title);

 

Dynamic text, with one variable

Wrong

Content of res/values/strings.xml:

<string name="current_date">Today is: </string>

Code in Activity’s onCreate() method:

titleView.setText(getString(R.string.current_date) + getFormattedDate());

Good

Content of res/values/strings.xml:

<string name="current_date">Today is: %s</string>

(IMPORTANT you can use other types of objects as formatting arguments, not only strings. You use %s - strings, %d - integers, more informations on java.util.Formatter reference page.
 
Code in Activity’s onCreate() method:

titleView.setText(getString(R.string.current_date, getFormattedDate()));

 

Dynamic text, with more than one variable

Good

Content of res/values/strings.xml:

<string name="dates_format">Start: %1$s, End: %2$s</string>

 
Code in Activity’s onCreate() method:

titleView.setText(getString(R.string.dates_format,
        getFormattedStartDate(), getFormattedEndDate()));
Reklamy

Skomentuj

Wprowadź swoje dane lub kliknij jedną z tych ikon, aby się zalogować:

Logo WordPress.com

Komentujesz korzystając z konta WordPress.com. Wyloguj / Zmień )

Zdjęcie z Twittera

Komentujesz korzystając z konta Twitter. Wyloguj / Zmień )

Facebook photo

Komentujesz korzystając z konta Facebook. Wyloguj / Zmień )

Google+ photo

Komentujesz korzystając z konta Google+. Wyloguj / Zmień )

Connecting to %s