Categories
android studio

How to make your own File Templates in Android Studio – Part 1

androidstudiofiletemplates

I have recently discovered something which is currently making my life easier at the moment: Custom file templates. What is a file template? A file template is a source file that already contains some code to get you started.

In this example, we are going to look at creating a file template for a RecyclerView adapter implementation which is something I often have to look up when trying to create it.

How to create your own file template in Android Studio:

  1.  Right click on a source code folder, hover over “New” then click “Edit File Templates”Custom File Template Editting
  2. Click the plus button to create a new template.Create New File Template
  3. You will then be able to give the template a name, in my case I will be creating a template for a RecyclerView adapter, so I will call it RecyclerViewAdapter .
  4. Then you will be able to paste or write your template code in the area below it. There are a couple of variables you can use that will get substituted when the user creates the file of their choice. Here are some predefined ones:
    • ${NAME}  is the file name that the user chooses
    • ${PACKAGE_NAME}  is the package name.
    • ${DATE}  the current date of the system.

You will also be able to define any custom variable that you need the user to input. In my example, I want the user to provide me with the ViewHolder  class that should be used (${VIEWHOLDER_CLASS})  and the List item class that should be used (${ITEM_CLASS}).

Now for the template code that will be used to create a new RecyclerView Adapter implementation:

https://gist.github.com/riggaroo/6db62da4ffbced347be5a217aea6a0e9

When you want to use the template, you will be prompted for all the values that are defined above such as ${VIEWHOLDER_CLASS}  and ${ITEM_CLASS} . These values will be substituted where the placeholders are defined. Very handy indeed.

  1. To use the template you have just defined, right click on a folder and click “New” and your template name will appear in the list.

Selecting custom template

Click the name and then fill in your variables:

File template custom variables

You will then see a beautifully generated class 😀.

GeneratedClassFromTemplate

Now I don’t need to look up RecyclerView adapters again! Yay!

Do you have any useful templates that you use? Please share them with me 😬

9 replies on “How to make your own File Templates in Android Studio – Part 1”

Wonderful idea! However, i think you can expand on it! Create a public git repository where templates are collected and shared 🙂

Hi Rebecca,
this post is awesome!!! 😀

Thank you very very much! 😉

Comments are closed.