Android Tips: Code Generation with Live Template

Tan Jun Rong avatar
Tan Jun Rong

For a long time I didn't know that Android Studio provides the feature to generate code.

👇

Generating Code
Generating Code

After knowing about this, I've been spamming only the logd generation for Log.d(TAG, "message"), but I never tried to configure my own Live Template.

Recently I've been trying to write an application from scratch, so whenever I tried to create a new Activity. I always have to create the following files:

  • SomeActivity
  • SomeViewModel
  • SomeRepository
  • SomeContract

And I realized most of their content are the same at the beginning. So as you can guess, it's a good fit for using Live Template! 😍

Here's an example of generating the RessetPasswordViewModel for the Password Resetting Page:

Generating ViewModel
Generating ViewModel

How to configure it

Here's a quick screenshot with 1,2,3,4 steps to do it:

Live Template Quick Steps
Live Template Quick Steps

Note that in step 3, you can key in any variable by surrounding it with dollar sign: $variable$. Other stuff is very easy that I don't have to explain it.

Sharing Live Template

I also discover that you can actually share your Live Template, this way I can share the creation of Activity, ViewModel, Repository, Contract with my team. Anyway you can share anything with your team.

To export Live Template, simple do this:

  1. File
  2. Export Settings
  3. Choose Live Template

To Import, do the same, but opposite:

  1. File
  2. Import Settings
  3. Select the file that is being exported

That's all for the quick tip, see you next time! 😀