Hello, I’m the light source.
In “Templating Android Projects to Dramatically Improve Android Development efficiency (Part 1)”, we learned how to use the Android Studio Template to significantly reduce the amount of work required to write business code, Also mentioned slightly is the use of Live Templates to reduce the “boilerplate code” involved in writing business code.
Some friends may ask, is it really necessary for us to be so efficient?
Instead of answering that question, let’s look at a scenario: writing a singleton.
The singleton pattern is probably one of the most common design patterns in development. Before writing a singleton, I always have to think about which of the various implementations of the singleton pattern should be used? Once you’ve chosen your implementation, you’ve written a bunch of code, and all of a sudden it’s the same except for the class name, is there a part of you that thinks it’s optimizable?
I don’t know how long it will take you to implement the singleton pattern, but let me tell you, we can do it in a second. Don’t you feel stupid writing code?
This is where the Live Template first comes in, making coding more efficient.
Following the above topic, there is another detail that some older programmers have their own default implementation of the singleton pattern, so don’t spend time worrying about it, right?
This is true, as I default to using internal static classes to implement singletons. But have you ever thought that project development is a team work process, even if the individual is not concerned, but in the case of multiple development, each person will have to use their own implementation method to cause the code style to be inconsistent, or colleagues will have to consult in advance and ask which is better. (The coding specification documentation doesn’t necessarily address these issues in detail.)
Think again, how can we unify scenarios that have multiple scenarios and are not part of the coding specification?
The answer is still Live Template. For example, in Android development, message.obtain () should be used to obtain an instance of Message, not to create a new one. Then we can specify a getMsg Live Template, as long as we use getMsg, Strict uniformity is guaranteed — this is another function of the Live Template, keeping the non-coding style of the project consistent. (The uniform code style of the coding nature is decisively implemented with the coding specification document)
Everyone here must have a certain attention and curiosity about Live Template, don’t worry, next dinner.
Introduction to Live Template
What is a Live Template? The real-time template mechanism simply means that some common code snippets are defined in advance and inserted into the editor while writing the code, using the method similar to code completion. The default shortcut is the Tab key (which may vary from platform to version). This article introduces Live Templates based on Android Studio 1.5+.
Go to Settings/Preferences -> Editor -> Live Templates and you can see the existing template groups.
As you can see, some templates already exist by default.
Open a group of a specific template, you can see a template contains abbreviations, description, content three pieces.
Review images
While writing code, type in the template abbreviation, press Tab, and the corresponding snippet is inserted in its current location.
The above is the simple use of Live Template, basically the same as ordinary code completion, especially simple and practical.
Of course, there are plenty of default templates, but we won’t stop there. Here’s how to customize templates.
2. Customize the template
Step 1 Create a new template
Go to Settings/Preferences -> Editor -> Live Templates, select a group, click the “+” sign in the upper right corner, and select Live Template.
Step 2 Select the application scope of the template
Click “Define” below to select the scope of application. Java if it works with class files, XML if it works with XML files.
Once the scope is selected, files outside the scope cannot use the template. For example, if the “LH” template of the Android XML grouping selects XML, it is not available in the class file.
Step 3 Fill in the content
As shown in Figure 2, a template consists of template abbreviation, description, and content.
-
The Template abbreviation is the name of the Template on the one hand, and the trigger identifier of Live Template on the other hand. It is recommended that the name be concise and not the same as the common class name or method name.
-
Description is a detailed description of the template, which is displayed to the user in the prompt.
-
The content is the concrete definition of the template and consists of ordinary code and variables.
In addition to writing dead content, template content can also declare and use variables. The variable form is. We can start creating variables for the current template by clicking on the “Edit Variables” button in the image below to open the variable definition window.
Review images
-
Name Specifies the variable Name, corresponding to variable_name
-
Expression Specifies the Expression of a variable
-
Default value Default value
-
Skip if defined Whether to Skip editing
The editor has defined some methods for Expression in advance. Some of the common methods are as follows:
methods | describe |
---|---|
Annotated (” annotation qname “) | annotations |
arrayVariable() | Set the variable |
className(sClassName) | The name of the class |
classNameComplete() | Current full class name |
complete() | Code completion |
componentTypeOf () | The type of the element in the collection |
date(sDate) | Current system date |
expectedType() | The type of the desired result, which is particularly useful in type conversions |
fileName(sFileName) | The file name with the extension |
iterableComponentType() | A traversable collection or array type |
lineNumber() | The line Numbers |
methodName() | The method name |
methodReturnType() | Method return type |
suggestIndexName() | Recommended index names (I /j, etc.) |
suggestVariableName() | Recommended variable name |
time(sSystemTime) | The system time |
typeOfVariable(VAR) | Variable types |
user() | Current user name |
(see https://www.jetbrains.com/help/idea/2016.1/live-template-variables.html#predefined_functions).
Three, take an example
As we all know, singletons are one of the most common patterns in program development. Although there are many implementations, no matter which one you choose, you can’t avoid writing boilerplate code repeatedly, and this scenario can be solved by using live Templates. Let’s use the template to create a singleton pattern to illustrate how to customize the template.
-
Go to Settings/Preferences -> Editor -> Live Templates, select a group, click the “+” sign in the upper right corner, and select Live Template.
-
Select Java as the application scope.
-
Fill in the abbreviation singleTon and describe it as a singleTon pattern. Then copy the following code into the template contents:
private static class SingleTonHolder {
private static final $class$ INSTANCE = new $class$();
}
public static $class$ getInstance() {
return SingleTonHolder.INSTANCE;
}
private $class$() {
}Copy the code
-
The class variable is defined here and will be created by clicking Edit Variables. The variable name is class, and Expression is className(). Click OK to save.
-
Once you have created a class, type singleTon and press TAB to see the singleTon template.
4. Live Template export and import
The first way is that the template data is stored as XML in the Android Studio Config \templates directory after the template is created. X \config\templates (user is your computer user name), Under the MAC for ~ / Library/Preferences/AndroidStudiox x/templates, exported file copy out of them; Similarly, you can import the defined XML files to the same directory.
The second option is to select only Live Templates through File -> Export Settings and Import Settings.
V. Project practice
For a specific project, custom Live templates can be divided into two parts. One is a relatively generic Template, which is used as a supplement to the default Template, such as the singleton pattern Template above. The other part is templates related to the depth of the project logic, such as using the project’s custom LogUtil instead of regular logs.
Examples of custom generic templates were given above, and examples of project-specific templates are given here.
For example, there is a toast utility class inside the project to display a toast, defining a template named “xxtoast” (prefixed to avoid conflicts with a regular toast), and the content is
ToastUtil.makeShortToast($strRes$);Copy the code
Finally, export these custom templates to GitLab, and other colleagues just need to clone these files to the corresponding directory for direct use.
Small tools
There is an Anroid Studio plug-in called Exynap that makes it easy to search, create, and use code snippets (not shared with Live Template) for those interested.
Six, reference materials
https://www.jetbrains.com/help/idea/2016.2/live-templates.html
Review images