Android

How to create live templates in Android Studio/Intellij IDE

Live Templates

We all agree with the fact that the Android studio has come a long way to be called as one of the best IDE when comparing with other IDEs but very few among us know about the hidden secrets that are available for the developers. So we will see:

Contents

How to  create live templates in Android Studio/Intellij IDE

Well first let me tell you what actually is Live Templates:

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

We have some built in live templates available in  Android studio

For e.g when we type psfi and press tab ,Android studio will automatically generate

public static final int and when we write psfs automatically public static final String.

Just imagine when you type the whole word many times in just a single file and multiply it in your whole application.Well it saves you hell lot of time.

There are predefined templates available like :

  • 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!

Well the most beautiful part is we can create our own templates also which can be utilised in any projects we are working on.

How to create your own Live template

Step 1:

For Mac users : Android Studio -> Preferences -> Live Templates.

For Windows and Ubuntu Go to File-> Settings-> Editor -> Live Templates.

You can see a window like below where you can see available templates

live_templates
live_templates

Step 2:Create “Template Group”

Click on the green plus button at right and create a “Template Group”. Give it a name say “CustomTemplates”. 

Now again 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.

In the example I am creating Live template for Recyclerview which is my favorite view.

I am using “rv” as abbreviation.

Step 3:Define “Context” of template

Define 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.

You can see the scopes for Java and other languages also.

You can also change the default button for invoking the template.Like if you are comfortable with some other key then you can change it.

live_templates
live_templates

Please comment which template you have created …

Top 10 tools to increase Android developers productivity

 

Feeling glad to receive your comment