Live Template In Android Studio

Introduction

 
Live templates help you to write more code with less effort. Live templates contain a predefined code structure. What if you could get a whole for loop with just one word? It seems interesting, let’s see how to live template can help to increase your productivity.
 
Live templates are code snippets that can be inserted in your code with their abbreviation and pressing tab. You can find all predefined live templates in the Editor section of your Android Studio.
 
 
Let’s understand it with a simple example, you have used this line so many times in your code.
  1. Toast.makeText(MainActivity.this,"Your message",Toast.LENGTH_SHORT).show();
But what if we can get this whole line with just one keyword? Just write Toast in your code, press tab and the whole code will be available for you in your editor.
 
 
 
You don’t even need to write your class name also, now let’s take a look at Live Template syntax of Toast.  
  • $className$ will return current class name.
  • “$text$” will be replaced by your given string. 

Custom Live Templates 

 
Step 1 - Go to File > Settings > Editor > Live Templates. Click the Android group, and press the plus button to add a new Live Template. 
 
Step 2 - Write your abbreviation and description for the Live Template.
 
Step 3 - Write below code in Template text area, 
  1. Intent intent=new Intent($className$.this,$destinationClass$.class);  
  2. startActivity(intent);    
Step 4 - Click on Edit variable and you will see following screen, assign className() expression to className variable.
 
 
Step 5 - At the bottom of your Template text you will find Define, just click on that and define coding language.
 
 
Step 6 
 
Click on Apply and you are done with your custom template, just use that abbreviation while you are coding and all the code snippets will we there in your code.
 

Summary

 
I know you all are having your own live templates and own coding styles, so feel free to share those templates in the comments and help your fellow developers to increase their productivity.


Similar Articles