Write More with Less in Android Studio
How to Use Live Template to Increase Developer Productivity
Live template is JetBrains IDE feature that allows you to expand keywords into code snippets with editable fields. When you’re typing in Android Studio, sometimes you will be prompted with this option:
Live template is very useful for day to day programming tasks, in which it:
- Improves developer’s productivity.
- Provides auto complete for frequently used codes.
- Provides customizable and editable fields based on the context of your code.
- Reduces cognitive burden because you don’t have to remember boilerplate codes.
In this article, I will try to explain how to create and apply custom live templates, and 2 other templates which can be useful to improve your productivity: Postfix Completion and File Templates
These templates are also available for other JetBrains IDE.
Live Template
There are some live templates which are provided by Android Studio out of the box, but those are mostly only for Java codes. For example, if we type logd
inside a function in Java code and select the prompted suggestion, it will complete your code into Log.d(TAG, “functionName: “);
.
You can also use “Insert Live Template” shortcut (Default to ⌘J on MacOS and Ctrl + J on Windows/Linux) to complete any valid Live Template abbreviation if you don’t remember it. For example, on MacOs, type log
and press ⌘J to see what happens.
To see existing or adding new live templates, go to
Settings/Preferences
then go toEditor | Live Templates
.
Creating a custom live template
To create a new live template, click Add (+) at the top right corner of live template window, then select Live Template. In the template window, give it an abbreviation. Abbreviation is the keyword that you will use to invoke your live template and expand it to template text.
You can use Template Group to organise your custom templates into logical groups.
A few things that we need to know before creating our live templates:
Context
When you create a new live template, you will be prompted with a warning message which says “No applicable contexts yet.” and there will be an option where you can define the context. This context will determine the type of files where the live templates will be available in.
Since we’re going to write live templates for Android, we will generally focus on Kotlin and XML context.
Tips: You can use the same abbreviation for different live templates that belong to different contexts. For example, you can define
logd
abbreviation in Kotlin context and it will only work when you’re typing in Kotlin file.
Variables
Variables are editable fields that can be changed at the time of usage. These variables can be user inputs or expressions that are evaluated by the IDE.
To add variables to your live templates, write $VARIABLE_NAME$
in template text field and then click Edit Variables. You should be able to edit your variables.
Here is the short explanation of each field:
- Name: The name of the variable.
- Expressions: Allows you to replace the variable with predefined functions.
- Default value: The value to be used if expression failed
- Skip if defined: Skips prompting user for input if expression is successfully evaluated.
There are 2 predefined variables that you can use: $END$
and $SELECTION$
.
$END$
is the position of the cursor after template is expanded.$SELECTION$
will be replaced by the code that is currently in selection when the template is expanded. This is useful when you’re using “Surround with Live Template”.
Examples of Custom Templates
Here are some live templates that I find really useful and use regularly:
Injectable lateinit var
Abbreviation:
injectContext:
Kotlin: classTemplate text:
@javax.inject.Inject
lateinit var $VARIABLE_NAME$
Tips: Use fully qualified name and ensure “Shorten FQ names” is enabled to allow Android Studio to automatically add necessary import statements.
Data Binding’s binding property
Abbreviation:
bindfContext:
Kotlin: classTemplate text:
private lateinit var binding: $BINDING_CLASS$override fun onCreateView(inflater: android.view.LayoutInflater, container: android.view.ViewGroup?, savedInstanceState: android.os.Bundle?): android.view.View? {
binding = $BINDING_CLASS$.inflate(inflater, container, false)
return binding.root
}Variables:
BINDING_CLASS
Expression:
classNameComplete()
If you wish to use it in an Activity
, you’ll have to create a separate live template.
Logging methods and parameters with Timber
Abbreviation:
timbermContext:
Kotlin: statementTemplate text:
timber.log.Timber.d($CONTENT$)Variables:
CONTENT
Expression:
groovyScript("def params = _2.collect {it + ' = [\$' + it + ']'}.join(', ');return '\"' + _1 + '() called' + (params.empty ? '' : ' with: ' + params) + '\"'", kotlinFunctionName(), functionParameters())
Make sure to press Enter after you finished typing in the expression field, otherwise it won’t be saved.
Android XML TextView with predefined style
Abbreviation:
textviewContext:
XML: XML textTemplate text:
<TextView
android:id="@+id/$ID$"
style="@style/Widget.WantedlyUI.TextView.$STYLE$"
android:layout_width="$VIEW_WIDTH$"
android:layout_height="$VIEW_HEIGHT$"
android:textAppearance="@style/TextAppearance.WantedlyUI.$STYLE$.$APPEARANCE$"$END$
tools:text="@tools:sample/lorem"
/>Variables:
ID
Default value:
"textView"VIEW_WIDTH
Expression:
enum("wrap_content","match_parent","0dp")
VIEW_HEIGHT
Expression:
enum("wrap_content","match_parent","0dp")
STYLE
Expression:
enum("Body1","Body2","Caption",...,"Title")
APPEARANCE
Expression:
enum("Regular","Medium","SemiBold","Bold")
In Wantedly, we have a design system that we can use to style our TextView
according to some predefined styles. Integrating this style
into our live template makes it easier for us to choose the correct appearance for our UI elements.
Your cursor will follow the ordering of parameters defined in the Variables, i.e., in this live template example, the cursor will go from
ID
,VIEW_WIDTH
,VIEW_HEIGHT
, thenSTYLE
even thoughSTYLE
was declared before bothVIEW_WIDTH
andVIEW_HEIGHT
in the Template text. This makes it easier for us to order the variables logically.
Postfix Completion
Postfix completion is very similar to live templates, but is invoked after an expression in your code. An example of postfix completion is .when
.
when statement from a variable.
To see existing postfix completions, go to
Settings/Preferences
then go toEditor | General | Postfix Completion
Unfortunately, although we can edit certain keywords and behaviors of postfix completion, we can’t add custom postfix completion for Kotlin at the moment. 😔
File Templates
Another feature that is very similar to live template is file template. File template is available when creating a new file using File | New
option.
To see existing or adding new file template, go to
Settings/Preference
then go toEditor | File and Code Templates
and selectFiles
tab.
To create a new file template, click + (Create Template) button at the top of the file templates window.
If you want to make use of live template inside your file template, ensure the “Enable Live Templates” checkbox below your template text is checked and add live template variable using
#[[$Var$]]#
format.
Example of File Template
For our Visit Android app, we use UseCase
class that wraps the business logic into a single place. This file template allows us to easily create a new UseCase
class that is also injectable.
#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME}#end
#parse("File Header.java")
class ${NAME} @javax.inject.Inject constructor() {
operator fun invoke(): #[[$Return$]]# {
#[[$END$]]#
}
}
File Header.java is the File Header template that you can find in the Includes tab.
Sharing your File Templates
To share your live templates with your team. You can check your template files, which are located in .idea/fileTemplates folder, into git. Then set your File and Code Templates’ Scheme to Project to tell Android Studio to use your file templates.
Live Template is a great feature that can easily improve your productivity as a developer. I have had a great experience with creating and using them and I hope that sharing my live template can inspire you to make your own live template. Let me know if there’s any interesting live template that I should know of!