Android Fall Sale

Get up to 55% off all Android books!

Live Templates in Android Studio: Getting Started

In this tutorial, you’ll learn how to use and create live templates in Android Studio so you can write code more quickly.

5/5 1 Rating

Version

  • Kotlin 1.3, Android 10.0, Android Studio 3.5

If you’ve spent time programming, you might have realized that there are some tasks you end up completing over and over again. This may be as simple as creating a function or building up a commonly used architecture. Either way, these tasks can start to feel tedious after so many repetitions. Shouldn’t you be using your brainpower to solve problems rather than type in the boilerplate code for a ViewModel again? In comes Live templates to the rescue.

Live templates are a feature that JetBrains thoughtfully included in IntelliJ, and by extension, Android Studio. By using them, you can quickly and intelligently add frequently used code patterns and constructs to your code, letting the IDE do the tedious work for you. This can help improve your productivity by providing some autocomplete and removing some of the cognitive burdens of boilerplate.

In this tutorial you’ll learn how to:

  • Use the live templates included in Android Studio.
  • Create custom templates.
  • Customize your templates for your needs.
  • Apply your new knowledge to generate entire files.

Time to get started!

Note: This tutorial assumes you have basic knowledge of Android and Kotlin. If you are new to Android development, check out our Beginning Android Development tutorials. Need to catch up on Kotlin? Take a look at Kotlin For Android: An Introduction.

Getting Started

To practice using and creating live templates you’ll be completing an app called What to Watch. This app will show you a random trending movie to take the time-consuming decision making out of your plans to watch a movie.

To get started, download the starter project using the Download Materials button at the top or bottom of this tutorial. Load the starter project into Android Studio and start to look around. Looks like you can’t build it yet! The MainActivity hasn’t implemented all the required interface methods. This is your task to complete throughout this tutorial. When you complete the app, it will look like this:

Final screenshot

This app follows a Model-View-Presenter or MVP architecture. While not the most recommended architecture, it’s a great playground for practicing using live templates. The main file you’ll be working in is MainActivity.kt. Get familiar with the following files before diving in:

  • MainActivity.kt: This activity is the main view of the app and implements an interface the presenter uses to instruct what to display.
  • MainView.kt: This file defines the interface that the MainActivity implements and the MainPresenter calls.
  • MainPresenter.kt: This class makes API calls through the MovieService, using the resulting data to call the view’s interface methods.
  • MovieService.kt: Here you use Retrofit to interface with the Trakt API to fetch some trending movies.

With that understood, you can get started building.

Generating an API Key

As with many API’s, you need an API key to use Trakt.

Trakt create app

To start, go to trakt.tv to sign in or create an account.

Trakt sign in page

Then you need to create an app. The name and redirect URI are required, everything else is optional. Fill in the form, and click Save App.

Trakt create app

Finally, copy the Client ID for your app.

Trakt api key

Paste your client ID in app ‣ build.gradle where it says YOUR KEY HERE, leaving the surrounding escaped quotation marks:

debug {
  // ADD YOUR API KEY HERE
  buildConfigField "String", "TRAKT_API_KEY", "\"YOUR KEY HERE\""
}

This puts your key where the MovieService can find it to use and find those movies. Sync your gradle file to make this new key available.

Now you’re all set to begin the work of finishing the MainActivity using live templates!

What is a Live Template?

As mentioned towards the beginning of this tutorial, a live template is a tool in Android Studio and IntelliJ that allows you to insert frequently used bits of code into your file. You may have even run into some by accident before. You’ll soon learn how customizable these can be!

You can use these templates anywhere you find yourself repeating the same patterns over and over. By learning them, you can spend less time typing and more time problem-solving!

Using Live Templates

To use a live template you start by typing in that template’s abbreviation. As you type, in the same way you have code completion, you will see live template abbreviations show up in a dropdown.

Simple Templates

Pick a Kotlin file such as MainActivity.kt to do some experimentation. At the bottom of the file, outside of the class, start typing the abbreviation psvma. Then, once you have the abbreviation typed or selected from the drop-down, hit Tab or Enter to insert a main method.

public static void main args expansion

The result should look like this:

fun main(args: Array<String>) {

}

Congrats! You just used a live template! Pretty painless, huh? Practice again by using the abbreviation sout to add a print statement to your main() method.

println("Hello World")

Notice how the cursor ends in just the right place after you insert the template? When you added the main() method it was in the body of the function, and when you added the print statement it was in the parenthesis. It may seem like movie magic, but there’s a simple way to learn how this is happening.

Viewing Templates

You can see the list of all live templates right in Android Studio. Go to Preferences ‣ Editor ‣ Live Templates. This is where you can find and explore all the live templates available to you. You’ll see a list with collapsed items. Navigate to Kotlin ‣ psvma.

Live template list

Some interesting things popped up on the bottom of the window when you selected that abbreviation. The abbreviation itself, a description, and the template text.

public static void main template

In the template text, you see all the code that was inserted plus the text $END$. This is a special variable that signifies where the cursor should be after the text is inserted. Not all templates have this, but you can see how helpful it is to have. If you look at sout, you’ll see it there too.

This is great, but not all code is that simple. You won’t name all functions main() and not all statements are to print things. Variables are powerful things to help with this, which you’ll start learning next.

Parameterized Templates

At the end of the file again, outside any function or class, insert the live template with the abbreviation fun2 to insert a function that takes two parameters. You’ll see something new: the opportunity to add your own input! To add a value for each input, type in the value, then press Tab to move to the next one until complete.

fun2 example

Use this template to create an add() function. Use the template, and don’t copy/paste:

fun add(a: Int, b: Int): Int {
  return a + b
}

Curious how this works? Open back up the list of live templates and find fun2 in the Kotlin list. The template you see will look a lot like this:

fun $NAME$($PARAM1$ : $PARAM1TYPE$, $PARAM2$ : $PARAM2TYPE$) : $RETURN$ {
$END$
}

There are so many more places where you see the pattern $<name>$. These are all variables. Unlike the special variable, $END$, these others are custom and allow user input. You can also use these to calculate the value instead of having the user enter it, but more on that later.

Surround Templates

One other thing you can do with templates is surround existing code. In your add() function, highlight a + b. Hit Alt-Cmd-J or Ctrl-Alt-J on Windows to bring up a popup where you can choose to surround your selection with parenthesis.

Surround with dropdown

Use the arrows keys to select Surround with () from the list, and hit Enter to use it. This surrounds your highlighted code with parenthesis!

You can find this template in the live template list under surround ‣ P. Similar to $END$, it uses a new special variable: $SELECTION$.

($SELECTION$)

This special variable can be used to surround some code with something else. You can take a look at the list of other surround templates to get an idea of how you can use it.

Now that you have this knowledge, you can use it to finish writing the MainActivity. Delete the scrap code you’ve been practicing with so you can get to the real deal.

Creating Live Templates

If you took a look at MainView.kt, you know that there are a bunch of show/hide methods to implement. You might predict the body of these methods will change the visibility of a view, and in some cases set the text. That’s a lot of repetition of the same logic. You’d probably be daydreaming of better times while writing that code by hand. Thankfully, you can make Android Studio do it for you after a little configuration!

To think about how you might want to create your template, you first need to picture what you want the result to look like. Start by imagining what the implementations of showProgress() and hideProgress() might be:

override fun showProgress() {
  progress.visibility = View.VISIBLE
}

override fun hideProgress() {
  progress.visibility = View.GONE
}

You need two methods, one that sets the visibility to VISIBLE and one that sets it to GONE. Open back up the live templates window to learn how to make a template for this.

As you’ve seen, there are many sublists of templates. They only matter for organizational reasons, and you can create a group if you need to. It’s suggested you put your custom template under other for this tutorial. Select other from the list, then click the + symbol on the right to create a new live template.

Add template

To represent show/hide view, enter shview for the abbreviation. Then, enter Add methods to show or hide a view for the description. To start building your template, paste in your final goal in the Template text box:

override fun showProgress() {
  progress.visibility = View.VISIBLE
}

override fun hideProgress() {
  progress.visibility = View.GONE
}

This is a great starting point. This is all ready to go if you only want to ever show and hide the progress view, but you can use variables to make it more flexible.

Adding Variables

To allow customization, you need to use variables. These always take the format of $<name>$, and you can use any name you want other than the reserved $END$ and $SELECTION$.

To think about where you might want to use variables, consider what will be consistent and what might change. You want to be able to change the function name to match the view and the view ID. Modify your template to use $VIEW$ and $VIEWID$, respectively. It should now look like this:

override fun show$VIEW$() {
  $VIEWID$.visibility = View.VISIBLE
}

override fun hide$VIEW$() {
  $VIEWID$.visibility = View.GONE
}

Notice how you’re able to reuse the same variable in multiple places, both in the show function and again in the hide function. This makes it so after you fill it in for the first function, the IDE will automatically copy it to where ever the variable is duplicated.

Setting Applicable Contexts

One last thing before you can use your template. Right under the template text, there is an option to define applicable contexts. Click on Define and select Kotlin ‣ Class.

Add context

This tells the IDE where this template can be used, in this case inside a Kotlin class. Now, this template will only be available when you’re writing code inside of a class.

Class context

Click OK to save your live template. Then use your new abbreviation, shview to implement the showProgress() and hideProgress() functions in your MainActivity:

override fun showProgress() {
  progress.visibility = View.VISIBLE
}

override fun hideProgress() {
  progress.visibility = View.GONE
}

Notice that because you didn’t use an $END$ variable, your cursor was placed at the end of the inserted code.

Note: If you’re having an issue with autocomplete inserting things you don’t want when trying to advance to the next variable, press ESC to dismiss the suggestion before pressing Tab to advance to the next variable. You’ll fix this later so you won’t need this workaround.

Yay! You successfully created and used your very own live template. You can use this template in other places, but looking at the rest of the interface you’re going to need to do more work. That means you get to make another template.

Creating a Complex Template

Most of the other show methods have some text as a parameter that needs to be set on a view. It makes sense, then, to create a template specifically for TextViews.

Start by considering the implementations for showTitle(title: String) and hideTitle(). They might look like this:

override fun showTitle(title: String) {
  text_title.text = title
  text_title.visibility = View.VISIBLE
}

override fun hideTitle() {
  text_title.visibility = View.GONE
}

This is pretty similar to the template you made before, with the addition of setting the passed in text. Open the live template window and create another new template. Use shtext for the abbreviation and Show/hide text view with value for the description. Just as before, copy in your end goal for show/hide title from above so you can start modifying it.

Thinking about what variables you might want to use, you can guess that you’d want the same ones as your previous template. In addition, you need one for the String that’s passed in. Modify your template to look like this:

override fun show$VIEW$($VALUE$: String) {
  $VIEWID$.text = $VALUE$
  $VIEWID$.visibility = View.VISIBLE
}

override fun hide$VIEW$() {
  $VIEWID$.visibility = View.GONE
}

This has the same $VIEW$ and $VIEWID$ variables you saw before. The additional $VALUE$ variable is used for that String you want to assign to the TextView.

Select Kotlin ‣ Class as the context, and click OK to save. Now use your new shtext template to add the title methods to your MainActivity:

override fun showTitle(title: String) {
  text_title.text = title
  text_title.visibility = View.VISIBLE
}

override fun hideTitle() {
  text_title.visibility = View.GONE
}

Nice! You could complete the MainActivity with these templates, but there’s still room for improvement. Keep reading to learn how!

Reordering Variables

You may be able to relate with the experience of forgetting the exact name of a view and relying on autocomplete to help you. In this case, it would be helpful to fill in the view ID variable before the method name. Good thing there’s a way to do that!

Open up your shtext template to edit. Next to the template text pane you’ll see a button labeled Edit variables. Click it to open up a new Edit Template Variables window here.

Edit variables window

There are many options here, but you’ll look at one of them to start: reordering. The table lists these variables in the order they will be filled in. You want the VIEWID variable first.

If it’s not already at the top of the list, select the VIEWID row. Then, use the arrows at the bottom of the list to move it to the top of the list. If you have a preference for the order of the other two variables, you can practice reordering with those as well.

Click OK to save the variable order, then OK again to save the template. Use your updated shtext template to add these tagline methods to your MainActivity:

override fun showTagline(tagline: String) {
  text_tagline.text = tagline
  text_tagline.visibility = View.VISIBLE
}

override fun hideTagline() {
  text_tagline.visibility = View.GONE
}

With this template, you’re able to fill in the view ID first to make sure you’re using the right name.

There’s still a lot of repetition in what you’re typing, so how about trying to clear that up more.

Reusing Variables

Because you’re following naming conventions, the name of the parameter is always part of the view ID. It would make sense, then, that you should only need to type this once. Because it’s a textual replacement, you can use the same variable in both places, including the text_ part of the ID in the template.

Open back up your shtext template to make that change:

override fun show$VIEW$($VIEWID$: String) {
  text_$VIEWID$.text = $VIEWID$
  text_$VIEWID$.visibility = View.VISIBLE
}

override fun hide$VIEW$() {
  text_$VIEWID$.visibility = View.GONE
}

This brings you back to having two variables to type in. You can do this because you’re always following the format of text_ followed by the name in your view IDs.

Save and use this template to add the year methods:

override fun showYear(year: String) {
  text_year.text = year
  text_year.visibility = View.VISIBLE
}

override fun hideYear() {
  text_year.visibility = View.GONE
}

You lost some of the autocomplete help, but you can solve that later on.

It still feels a little silly to have to type the same word twice, once uppercase and once lowercase. There’s one more fancy trick to use to get around this.

Using Predefined Functions

There are a few predefined functions you can use in your templates to make your life easier. These include things like inserting the current class name and changing the case of a String. You can see the full list of options in the documentation.

What you need for your template is the capitalize() function. You can pass in what you type for the view ID in lowercase and insert the uppercase version in the method name.

To do this, you need to open the Edit variables window for your template. You use predefined functions in the Expression column. Add the expression capitalize(VIEWID) to the Expression column for VIEW, and press Enter.

Use capitalize function

There are three things you can pass into predefined functions that take a parameter:

  1. Another variable.
  2. A String surrounded by quotes.
  3. Another function.

Here, you’re using the first option to pass in the VIEWID variable.

Before you save it and try it out, select the Skip if defined checkbox in the VIEW row. This says that if the value is already defined, such as if by an expression, don’t ask the user to fill it in.

Click OK and save your template. Insert the overview methods to test out your changes:

override fun showOverview(overview: String) {
  text_overview.text = overview
  text_overview.visibility = View.VISIBLE
}

override fun hideOverview() {
  text_overview.visibility = View.GONE
}

Yay! Now you only need to type the name once to create these methods. So little typing, so much code. Only one pair of methods left to implement.

Combining Functions

The last two interface methods you have to implement are showErrorMessage(errorMessage: String) and hideErrorMessage(). Are you able to spot the issue with our current template for writing these?

The method name should be PascalCase, the parameter name should be camelCase, and the view ID should be snake_case. Back to template editing to fix this!

We need all three variables again to have all three behaviors. Revert the template text to include three variables:

override fun show$VIEW$($VALUE$: String) {
  text_$VIEWID$.text = $VALUE$
  text_$VIEWID$.visibility = View.VISIBLE
}

override fun hide$VIEW$() {
  text_$VIEWID$.visibility = View.GONE
}

This adds that $VALUE$ variable back in.

Next, you need to edit the expressions for the variable. You can use both the capitalize() and camelCase() functions for this. Open up the Edit variables window.

First, make sure the VIEWID is the first variable in the list. This is the one you want to type in with the help of autocomplete.

Then, to make sure the parameter is camelCase, give VALUE the expression of camelCase(VIEWID). Make sure Skip if defined is selected.

Finally, use capitalize(camelCase(VIEWID)) for VIEW to use both camelCase and capitalization in the method name. Notice how you’re able to pass one function to another. You should also check Skip if defined for VIEW.

In the end, your variables should look like this:

Final variables

Note: You can also use capitalize(VALUE) for VIEW because VALUE is already camelCase.

Save your variables and template. Try out your template by adding the very last interface methods:

override fun showErrorMessage(errorMessage: String) {
  text_error_message.text = errorMessage
  text_error_message.visibility = View.VISIBLE
}

override fun hideErrorMessage() {
  text_error_message.visibility = View.GONE
}

All the capitalization is “magically” taken care of for you!

You’ve worked hard, and it’s time to see your hard work pay off. Build and run the app. You now have the answer to what movie you should watch next!

Final screenshot

Tips and Tricks

While you’re all set to hit the ground running with live templates, there are some other tips you can learn to go along with your new knowledge.

Default Expand With

If you don’t like expending your live templates with a Tab, you can specify what other key you’d like to use. In the live templates preferences, you can set what you want to use both for the default of all templates, as well as per template.

Default expand with option

Postfix Completion

Very similar to live templates is postfix completion. You can use this by typing a . followed by the keyword in your code. At the top of showTagline(), start typing tagline.isBlank().if.

Postfix completion

Select the if option and watch an if statement expand before your eyes. You can use this if statement to only show the tagline if the String is not blank if you like.

if (tagline.isBlank()) {
  hideTagline()
  return
}

While you can’t create your own Kotlin postfix templates at the time of this writing, you can see the list of available ones at Preferences ‣ Editor ‣ General ‣ Postfix Completion.

File Templates

Just like you have a file for a statement or a method, you can have a template for an entire file. To see the list of these or make your own, go to Preferences ‣ Editor ‣ File and Code Templates. The file templates work slightly different than live templates, so it’s great to look at existing ones for inspiration.

Under the Files tab, try making a new one for a view interface. Click the + at the top of the list, enter View Interface for the name and kt for the extension. Finally, add the following to the body:

#parse("File Header.java")
#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME}

#end
interface ${NAME} {
  fun showErrorMessage(errorMessage: String)
  fun hideErrorMessage()
  fun showProgress()
  fun hideProgress()
}

Click OK to save. This creates a generic interface with show and hide methods for both error and progress views. Now, when you go to create a new file, you have this option.

Create new view interface

Challenge

You’ve learned so much about live templates in this tutorial. As a challenge to exercise your new knowledge, for your first shview template you made, apply what you’ve learned to:

  • Change the order of variables.
  • Use the capitalize() function to only type the view name once.
  • Skip the variable if defined

You can find the solution in the final project.

Where To Go From Here

You can download the final project using the Download Materials button at the top or bottom of this tutorial. To import the live templates included in the project you need to select File ‣ Import Settings, select settings.zip from the root of the final project, and make sure you check Live templates before clicking OK. You’ll need to restart Android Studio before you see the imported templates.

Import live templates settings

Note: You’ll need to add your Trakt API key to run the final project.

Hopefully you’re starting to think of all the places you can start to use live templates. To get ideas on where you can use them you can look at:

You can also learn more about live templates by looking at the JetBrains documentation:

Did you think of a cool place to use live templates? Have any questions or comments? Join the discussion in the forum below!

Average Rating

5/5

Add a rating for this content

1 rating

Contributors

Comments