17 September 2016

String formatting and Lint

One piece of advice that we keep hearing over and over is to extract strings into resources. There really is no reason for you to hard code strings in code.

I wrote before about easily moving strings between Java and XML, and today I'd like to focus on string formatting. The Android dev guide gives a good overview of the support Android has for passing arguments into a String.format(String, Object...).

Worried about using incorrect syntax? I was! I can never remember which of the % or the $ comes first, or if I'm passing arguments in the correct order. To be clear, the syntax is
%[arg number]$[arg type]


Thankfully, Android Studio has come a long way with pointing us in the right direction when working with strings.

First off, a very useful warning when setting manually concatenated text into a TextView:
 And by "placeholders" they mean the format arguments.

You can mix and match multiple arguments and argument types in one string too!

And in case you removed an argument in the XML file but forgot to edit code, another helpful error for you!

If you change the argument type, Studio will tell you about it too.

If you forget the syntax, fear not for Studio will tell you. (May not be too obvious here but I used the incorrect "$1$s" format.)

Android Studio is really so helpful now, we are running out of excuses to be lazy coders. 😱