Skip to content

Tag: i18n

Android: acessing internal resoures

a new android I just drew. source-code: android_look.svg. CC-BY-SA as usual.

You can acess internal Android resources such strings, drawables, layouts and others. For example, if you need to create a button with the text “Cancel” you can do:

Using this you are using the internal resource for “Cancel” in that Android and all its i18n. Using the same logic you can access drawables, layouts, etc.

Beware the locale

See-ming Lee 李思明 SML Photo

Today I was programming a toString method for a class widely used in a application, using the very useful String.format that provides a C’s like printf formatter.

@Override
public String toString() {
   return String.format("VO[a: %.1f, b: %.1f, c: %.1f]", a, b, a+b);
}

%.1f means a float with one digit precision after the dot separator. The code produces something like:

VO[a: 1.0, b: 2.0, c: 3.0]

The problem arises when running a JUnit test on this method wrote using a regular expression to extract the values from the String to test it correctness. We cannot assume that the dot will be always the separator for displaying a float value, in my locale pt_BR would be a comma. So the output would be:

VO[a: 1,0, b: 2,0, c: 3,0]

For a predictable output we can set a Locale for String.format:

Locale en = new Locale("en");
return String.format(en, "VO[a: %.1f, b: %.1f, c: %.1f]", a, b, a+b);

So it will always use the dot as common separator. Of course you should follow and respect the localization and internationalization efforts in others moments but in this toString case we are using it internally for debug and unitary testing so we can set a English default locale for safety reasons.