Mallow's Blog

How to create a template in Android Studio

Templates: 

Templates are prewritten modules that can be used for repeated use. You can create code templates with the help of Android design studio to get elements that follow the Android design & development standards. This makes the process of Android app development easy. In this post, we are going to see the step by step process of creating a template with the help of Android Studio.

For creating new templates:

In the Android studio.

Right click on the source code folder and select “New”, then select “Edit File Templates”.

Then you will see a window like in the picture below:

Here you can see some predefined templates but we don’t need this so click on “+” icon in the top left corner. After this action, your screen should look like this.

In the field called “Name:” enter a name for your template. The name should be “ViewPagerTemplate”.

Now we are ready for some fancy template coding in the big area below template name. For defining some custom variable, write ${VARIABLE NAME}. Entry for the variable name will be displayed during class creation, also here are some predefined ones: ${PACKAGE_NAME}, ${NAME}, etc.

Example 1.

In this example we will use only predefine variables. ViewPagerAdapter template code is shown below:

package ${PACKAGE_NAME};
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import java.util.ArrayList;
public class ${NAME} extends FragmentStatePagerAdapter {
private ArrayList fragmentArrayList = new ArrayList();
public ${NAME}(FragmentManager fm, ArrayList fragmentArrayList) {
super(fm);
this.fragmentArrayList = fragmentArrayList;
}
@Override
public Fragment getItem(int position) {
return fragmentArrayList.get(position);
}
@Override
public int getCount() {
return fragmentArrayList.size();
}
}

Example 2.

In second example shown below, we will be using singleton class and predefined variables.

#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME};#end
#parse("File Header.java")
public class ${NAME}{
private static ${NAME} ourInstance = new ${NAME}()
public static ${NAME} getInstance()
return ourInstance;
    }
    private ${NAME}() {
   }
}

How to use Templates :

First select the package where you want to generate your template code. Then choose “New” and select a template.

After selecting a template, you have one more than step – writing variable entries.

Conclusion:

We have seen in detail about the creating a template in Android studio. Creating a template helps in reducing the development process considerably and also eases the coders to create extensive projects.

MANIKANDAN K,
Android application developer,
Mallow technologies private limited.

2 Comments

  1. Saravanakumar B

    Nice Tutorial

    1. Gopal

      Thank you !!

Leave a Reply

%d bloggers like this: