Live Templates in Android Studio: From Built-In to Custom Shortcuts
Android Studio's Live Templates feature significant accelerates coding by providing predefined code blocks triggered by simple keywords or suffixes. This article covers built-in templates and demonstrates how to create custom ones tailored to your workflow.
Understanding Live Templates
Live Templates are shorthand strings that expand into common code structures. They are configured under Settings → Editor → Live Templates. There are two activation modes:
- Full keyword type: Type a keyword and press Enter (e.g.,
logeexpands toLog.e(TAG, "");). - Postfix type: Type an object, a dot, then a keyword and press Enter (e.g.,
view.notnullexpands to a null check).
Essential Built-In Full Keyword Templates
fbc— Expands tofindViewByIdwith proper cast:private Button button; button = (Button) findViewById(R.id.button);const— Defines an integer constant:private static final int CONST_NAME = 0;key— Defines a String constant:private static final String KEY_NAME = "";psf— Createspublic static finalfield.fori— Generates a standardforloop over an index variable.sout— Expands toSystem.out.println();.ifn— Creates a null checkif (variable == null) { }.inn— Creates a not-null checkif (variable != null) { }.gone— Sets visibility toGONE:view.setVisibility(View.GONE);.rouiT— Wraps code in arunOnUiThreadblock:runOnUiThread(new Runnable() { @Override public void run() { // code } });Sfmt— Quickly formats a string usingString.format().ViewConstructors— Generates all three constructors for a custom View class.
Essential Built-In Postfix Templates
Apply these after an expression (object, variable, etc.):
.notnull/.null— Surrounds with null check..var— Declares a local variable initialized with the expression..field— Creates a class-level field initialized with the expression..for— Generates an enhanced for-each loop..fori— Generates a standard for loop over an array or list..forr— Generates a reverse for loop..return— Returns the expression..cast— Casts the expression to a type..try— Wraps the expreession in a try-catch block..format— Wraps the string expression inString.format()..switch— Creates a switch statement using the expression.
Creating Custom Live Templates
Custom templates save time on repetitive patterns. First, create a new group (e.g., MyTemplates) under Live Templates.
1. Singleton Pattern
- Abbreviation:
sin - Description: Generates a thread-safe singleton.
- Template text:
private static final $CLASS$ ourInstance = new $CLASS$(); public static $CLASS$ getInstance() { return ourInstance; } private $CLASS$() {} - Edit variables: Set variable
$CLASS$with expressionclassName().
2. Activity Click Listener
- Abbreviation:
click - Template text:
public void onClick(View view) { switch (view.getId()) { case R.id.$resId$: $content$; break; default: break; } } - Edit variables: Define
$resId$(no expression, just a placeholder) and$content$(no expression).
3. Location-Aware Log
-
Abbreviation:
dl -
Template text:
Log.e("$class$", "$method$($class$.java:$line$)" + $content$); -
Edit variables:
$class$— expression:className()$method$— expression:methodName()$line$— expression:lineNumber()$content$— no expression
The logcat output becomes clickable because it contains the pattern
(ClassName.java:lineNumber). If additional lines are added later, the line number becomes inaccurate. Consider using a logging utility like ELog for robust tracking.
4. Switch Statement Skeleton
- Abbreviation:
sw - Template text:
switch ($content$) { case $value$: $code$; break; default: break; } - Edit variables:
$content$,$value$,$code$are plain placeholders.
5. Non-Empty String Check
- Abbreviation:
nes - Template text:
TextUtils.isEmpty($content$)
Configuring Variable Expressions
When editing variables for a custom template, you can use predefined expressions:
| Expression | Description |
|---|---|
className() |
Returns the current class name. |
methodName() |
Returns the current method name. |
lineNumber() |
Returns the current line number. |
groovyScript("...") |
Executes a Groovy script for advanced transformations. |
The Skip if defined checkbox makes the cursor skip that variable if a default value is already set, moving directly to the next editable field.
For the complete list of expressions, refer to the IntelliJ documentation.
Custom templates can be exported and shared; the author's collection is available on GitHub.