Writing more code by writing less code with Android Studio Live Templates

Ngoc Huynh

If you’ve written much Android code, you’ve probably made this mistake at least once:

Toast.makeText(MainActivity.this, “This will not be displayed”);

Unless you’re getting paid by the keystroke, no one wants to write repetitive boilerplate code. It’s easier to show than explain, so here’s how they work.

As you can see, Live Templates are shortcuts displayed as code-completion options that, when selected, insert a code snippet that you can tab through to specify any required arguments.

For example, as shown above — typing “Toast” then hitting the Tab key inserts the code for displaying a new Toast with argument placeholders that you can enter, before hitting tab and moving on to the next argument.

Android Studio Live Templates: A Handy Reference

IntelliJ includes over dozens of Live Templates, and Android Studio features another 48 specific for Android development. Here’s a few of my favorites for easy reference.

Live templates can also insert larger code snippets; such as starter which creates a static start(…) helper method to start an Activity:

public static void start(android.content.Context context) {
android.content.Intent starter = new Intent(context, $ACT$.class);

You can use the File > Settings > Editor > Live Templates menu option to see the full list.

Of course, if your favorite boiler plate isn’t already there, remember that you can:

Go to File > Settings > Editor > Live Templates. Click the Android group, and press the plus button to add a new Live Template.

You’ll want to choose an abbreviation to use the template, a description to remember what it does, and of course the code you’d like it to insert — like this example for writing a boolean Shared Preference value.

android.content.SharedPreferences sharedPreferences =
android.content.SharedPreferences.Editor editor =
editor.putBoolean(getString(R.string.$stringVal$), $spVal$);

Notice that we’re fully qualifying the class paths, and most importantly that we replace the parts of our code snippet that will be different each time with variables indicated by wrapping the names with matching $ symbols.

With our new Live Template defined, we can type the abbreviation — select it from the autocompletion hint by pressing tab — and it will paste in our code snippet!

Share the news now

Source : https://medium.com