Categories
android studio

How to create your own Live Templates in Android Studio/IntelliJ – Part 2

In the last post we looked at how to create a File Template in Android Studio. In this post we will look at Live Templates and how to make your own.

Live templates are “frequently-used or custom code constructs that you can insert into your source code file quickly, efficiently and accurately.”

For example, type psfi  and press enter in Android Studio. It will automatically generate the words public static final int. That saves you 19 keystrokes! 😜There are already some predefined live templates that you can use:

  • logm  – logs your method name being called with its arguments that were passed to it. (I find this one the most useful)
  • psfs  – Replaces with public static final String
  • .null  – When you want to surround your code with a null check, instead of typing if ( item == null){ } . Type item followed by .null , then press enter. This will surround the object with a null check!

This is awesome right? What is even better is the ability to create your own Live Templates.

How to create your own Live template

  1. Head to Android Studio -> Preferences -> Live Templates. (Here you will also see the list of available templates. It is worth glancing over them as you might find some useful ones.)Live Templates Android Studio
  2. Click on the plus button and create a “Template Group”. Give it a name.
  3. Then click the plus button again and select “Live Template”. You will then be able to specify the abbreviation you want to use and a brief description of the template. You then need to specify the template text. This is what the abbreviation will be replaced with when you type the abbreviation.Custom Live Template CreationDefine the context of the template by clicking “Define“, in this case, I will select “XML” as that is what kind of file I want this template to be available in.
  4. Click OK and then use it! To use it, type the abbreviation you have created and tab or enter will replace it with the template text.recyclerview cusotm live template

There we have it, custom live templates!

livetemplate

What live templates have you made?

5 replies on “How to create your own Live Templates in Android Studio/IntelliJ – Part 2”

This will be very helpful in creating Toast and Dialog.
When I’m working on lengthy projects I usually make a method for Toasts like showToast(String text, String length). Now I would want to use live template instead 🙂

And while we’re talking about Toasts, I want to take a moment to mention that it is also crazy of android to allow us to complete the code without invoking show(), but then immediately tell us to use show() method asap. I think this method should be inherent in Toast.makeText().

Comments are closed.