Android Studio Live Templates

One of best programming practices is DRY. Don’t repeat yourself. And yet we often write similar blocks of code over and over again. And sometimes it really cannot be avoided. You can save yourself lot of time when you meet Android live and file templates. In this post, I write about live templates but I am sure I will come back to file templates later.
So how can you use live templates? Simply type template abbreviation, press Tab and block of code defined in template comes up. There are many live templates already included in Android Studio, but you can also define your own. To see them go to Editor, Settings and Live Templates. There they are, by default sorted by a programming language of their use. Looking like this.

Live templates are not Android and Android Studio specific feature, they can be used also in IntelliJ Idea and other JetBrains IDEs.

Live template details

Lets check few examples to learn how to write your own.

const

private static final int $name$ = $value$;

Template contains hardcoded text and variables (between $). These are things that you type yourself. So you type const, press Tab (or other key you can select in settings) and hardcoded text shows up together with cursor at the place of first placeholder. Type what fits in and press Return or Tab to finish or skip to next placeholder. If same variable name is used more times, values you type once will be entered everywhere.

But you don‘t need to type content of every variable. You can inject expression result into a variable placeholder. For example, const from our example has defined following expression for the variable value.

groovyScript("new Random().nextInt(1000)")

All templates have the context where they can be used. They can be used everywhere or only at a specific type of file (like Java, Kotlin or XML). But context might be more specific.

Few more examples

Lets look at few more useful default templates.

Loge

android.util.Log.e(TAG, "$METHOD_NAME$: $content$", $exception$);

This one uses for variable METHOD_NAME expression methodName()

newInstance

public static $fragment$ newInstance($args$) {
    $nullChecks$
    android.os.Bundle args = new Bundle();
    $addArgs$
    $fragment$ fragment = new $fragment$();
    fragment.setArguments(args);
    return fragment;
}

Here variable fragment comes with expression className()

todo

// TODO: $date$ $todo$ 

I am sure every programmer loves this one. Here variable date comes with expression date().

I suggest you check Live templates. You can find a lot of useful predefined templates in here. And you can easily write your own. Live templates are a powerful tool that will enable you to write code faster.