When working on an Android project, you will frequently need to create several components such as ViewModel, Repository, and so on. To create a new ViewModel, for example, you must first create a new Kotlin class, name it, then extend it with the ViewModel() class.
If you’re using a DI tool like Hilt, you’ll need to add additional boilerplate code, such as @HiltViewModel and @Inject constructor().
This is a time-consuming process that should be avoided. But how exactly?
Meet File templates
File templates are specifications of the default contents for new files that you create. Depending on the type of file you are creating, templates provide initial code and formatting expected in all files of that type.
Suppose you want to create a file template for a Hilt-based ViewModel class that includes both the ViewModel and Hilt related oe.
To create a file template called ViewModelTemplate,
1. Press Ctrl+Alt+S (or File->Settings) and go to Editor -> File and code templates.
2. On the Files tab, click the Add button and enter the template name, file extension, resultant file name, and template body (as following).
#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME}
#end
#parse("File Header.java")
import javax.inject.Inject
import dagger.hilt.android.lifecycle.HiltViewModel
import androidx.lifecycle.ViewModel
@HiltViewModel
class ${NAME} @Inject constructor(
): ViewModel() {
}
3. Apply the changes and close the dialog.
To use this file template, do the following
1. Right click on package name, select New -> ViewModelTemplate (or File -> New -> ViewModelTemplate)
2. Give ViewModel a name.
3. You’ll have ViewModel class with all boilerplate code.