This document describes the format and syntax for Android code templates. These templates provide starting points for entire projects (e.g. NewAndroidApplication
) or application components such as activities (e.g. BlankActivity
).
Although these templates were originally introduced in the ADT Plugin for Eclipse, the template format is designed for use by any IDE or command-line tool.
Templates are customizable. Each template exposes several options (called parameters) that allow developers to customize the generated code. The most common workflow for using a template is as follows:
Templates make heavy use of FreeMarker, a Java templating engine used to enable things like control flows and variable substitutions inside files. It's similar to PHP, Django templates, etc. For those more acquainted with C/C++, think of it as a preprocessor language (i.e. #ifdef
).
By convention, any file in the template directory structure that is to be processed by FreeMarker should have the .ftl
file extension. So if one of your source files is MyActivity.java
, and it contains FreeMarker instructions, it should be named something like MyActivity.java.ftl
.
For more documentation on FreeMarker, see the docs. In particular, the reference on string operations.
An example, templated version of an Android manifest, normally named AndroidManifest.xml.ftl
is shown below.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"> <application> <activity android:name=".${activityClass}" android:label="@string/title_${activityToLayout(activityClass)}"> <#if parentActivityClass != ""> <meta-data android:name="android.support.PARENT_ACTIVITY" android:value="${parentActivityClass}" /> </#if> <#if isLauncher> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </#if> </activity> </application> </manifest>
In this example excerpt from the BlankActivity
template:
${activityClass}
is bound to the value of the 'Activity Class' template parameter.${activityToLayout(activityClass)}
uses the activityToLayout
method built into ADT to convert an activity class such as MyFooActivity
to activity_my_foo
.isLauncher
boolean variable and parentActivityClass
string varaibles are bound to the values of the 'Launcher Activity' and 'Hierarchical Parent' template parameter, respectively.A template is a directory containing a number of XML and FreeMarker files. The only two mandatory files are template.xml
and recipe.xml.ftl
. Template source files (PNG files, templated Java and XML files, etc.) belong in a root/
subdirectory. An example directory structure for a template is below:
More on the role of each of these files is discussed in the sections below.
Each template directory must contain a template.xml
file. This XML file contains metadata about the template, including the name, description, category and user-visible parameters that the IDE will present as options to the user. The XML file also indicates the name of the recipe XML file (which gets processed by FreeMarker), and the global variables XML file if there are global variables besides the template parameter values that should be visible to all FreeMarker-processed files (.ftl
files).
An example template.xml
is shown below.
<!-- A template for a blank activity. Use template format version 3, as described in this document. --> <template format="3" revision="1" minApi="4" minBuildApi="11" name="New Blank Activity" description="Creates a new blank activity, with navigation."> <!-- Indicate that the Android Support Library (r8) should be added to the project, if it isn't already in the project. --> <dependency name="android-support-v4" revision="8" /> <category value="Activities" /> <!-- A string parameter; the value is available to FreeMarker processed files (.ftl files) as ${activityName}. --> <parameter id="activityName" name="Activity Name" type="string" constraints="class|unique|nonempty" suggest="${layoutToActivity(layoutName)}" default="MainActivity" help="The name of the activity class to create." /> <parameter id="layoutName" name="Layout Name" type="string" constraints="layout|unique" suggest="${activityToLayout(activityClass)}" default="main" help="The name of the layout to create for the activity" /> <parameter id="navType" name="Navigation Type" type="enum" default="none"> <option id="none" default="true">None</option> <option id="tabs" minApi="11">Tabs</option> <option id="pager" minApi="11">Swipe Views</option> <option id="dropdown" minApi="11">Dropdown</option> </parameter> <!-- 512x512 PNG thumbnails. --> <thumbs> <!-- Default thumbnail. --> <thumb>template_default.png</thumb> <!-- Attributes act as selectors based on chosen parameters. --> <thumb navType="tabs">template_tabs.png</thumb> <thumb navType="dropdown">template_dropdown.png</thumb> </thumbs> <!-- Optional global variables. --> <globals file="globals.xml.ftl" /> <!-- Required recipe (script) to run when instantiating the template. --> <execute file="recipe.xml.ftl" /> </template>
Below is a listing of supported tags in template.xml
.
The template root element.
format
3
.revision
name
description
minApi
minSdkVersion
no lower than this value before instantiating the template.minBuildApi
Indicates that the template requires that a given library be present in the target project. If not present, the IDE will add the dependency to the project.
name
android-support-v4
android-support-v13
revision
The template type. This element is optional.
value
Applications
Activities
UI Components
Defines a user-customizable template parameter.
id
foo
, the parameter value will be available in FreeMarker files as ${foo}
.name
type
string
, boolean
, enum
, or separator
.constraints
|
. Valid constraint types are: nonempty
— the value must not be emptyapilevel
— the value should represent a numeric API levelpackage
— the value should represent a valid Java package nameclass
— the value should represent a valid Java class nameactivity
— the value should represent a fully-qualified activity class namelayout
— the value should represent a valid layout resource namedrawable
— the value should represent a valid drawable resource namestring
— the value should represent a valid string resource nameid
— the value should represent a valid id resource nameunique
— the value must be unique; this constraint only makes sense when other constraints are specified, such as layout
, which would mean that the value should not represent an existing layout resource nameexists
— the value must already exist; this constraint only makes sense when other constraints are specified, such as layout
, which would mean that the value should represent an existing layout resource namesuggest
suggest
against each other's values, but these expressions are only updated for non-edited values, so this approach lets the user edit either parameter value, and the other will automatically be updated to a reasonable default.default
help
For parameters of type enum
, represents a choice for the value.
id
minApi
minSdkVersion
no lower than this value before instantiating the template.[text]
Represents a thumbnail for the template. <thumb>
elements should be contained inside a <thumbs>
element. The text contents of this element represent the path to the thumbnail. If this element has any attributes, they will be treated as selectors for parameter values. For example, if there are two thumbnails:
<thumbs> <thumb>template.png</thumb> <thumb navType="tabs">template_tabs.png</thumb> </thumbs>
The template 'preview' thumbnail will show template_tabs.png
if the value of the navType
template parameter is tabs
and template.png
otherwise.
The optional globals XML file contains global variable definitions, for use in all FreeMarker processing jobs for this template.
An example globals.xml.ftl
is shown below.
<globals> <global id="srcOut" value="src/${slashedPackageName(packageName)}" /> <global id="activityNameLower" value="${activityName?lower_case}" /> <global id="activityClass" value="${activityName}Activity" /> </globals>
The recipe XML file contains the individual instructions that should be executed when generating code from this template. For example, you can copy certain files or directories (the copy instruction), optionally running the source files through FreeMarker (the instantiate instruction), and ask ADT to open a file in Eclipse after the code has been generated (the open instruction).
Note: The name of the recipe file is up to you, and is defined in template.xml
. By convention, however, it's best to call it recipe.xml.ftl
.
Note: The global variables in globals.xml.ftl
are available for use in recipe.xml.ftl
.
An example recipe.xml.ftl
is shown below.
<recipe> <!-- runs FreeMarker, then copies from [template-directory]/root/ to [output-directory]. --> <instantiate from="AndroidManifest.xml.ftl" /> <!-- automatically creates directories as needed --> <copy from="res/drawable-hdpi" /> <copy from="res/drawable-mdpi" /> <copy from="res/drawable-xhdpi" /> <copy from="res/values/dimens.xml" /> <copy from="res/values/styles.xml" /> <copy from="res/values-large/dimens.xml" /> <copy from="res/menu/main.xml" to="res/menu/${activityNameLower}.xml" /> <instantiate from="res/values/strings.xml.ftl" /> <!-- Decide which layout to add --> <#if navType?contains("pager")> <instantiate from="res/layout/activity_pager.xml.ftl" to="res/layout/activity_${activityNameLower}.xml" /> <#elseif navType == "tabs" || navType == "dropdown"> <copy from="res/layout/activity_fragment_container.xml" to="res/layout/activity_${activityNameLower}.xml" /> <#else> <copy from="res/layout/activity_simple.xml" to="res/layout/activity_${activityNameLower}.xml" /> </#if> <!-- Decide which activity code to add --> <#if navType == "none"> <instantiate from="src/app_package/SimpleActivity.java.ftl" to="${srcOut}/${activityClass}.java" /> <#elseif navType == "pager"> <instantiate from="src/app_package/PagerActivity.java.ftl" to="${srcOut}/${activityClass}.java" /> <#elseif navType == "tabs"> <instantiate from="src/app_package/TabsActivity.java.ftl" to="${srcOut}/${activityClass}.java" /> <#elseif navType == "dropdown"> <instantiate from="src/app_package/DropdownActivity.java.ftl" to="${srcOut}/${activityClass}.java" /> </#if> <!-- open the layout file when done --> <open file="res/layout/${activityNameLower}.xml" /> </recipe>
The instructions below are supported:
The only required argument is from
which specifies the location of the source files to copy under the root/
directory. All necessary ancestor directories are automatically created if needed.
The default destination location is the same path under the output directory root (i.e. the location of the destination project). If the optional to
argument is provided, this specifies the output directory. Note that if the from path ends with .ftl
, it will automatically be stripped. For example <instantiate from="res/values/strings.xml.ftl" />
is adequate; this will create a file named strings.xml
, not strings.xml.ftl
.
This argument works recursively, so if from
is a directory, that directory is recursively copied.
Same as <copy>
, but each source file is first run through FreeMarker.
This instruction will be used to merge the contents of a source file into an existing file in the project. The most common use case for this will be to add components to the AndroidManifest.xml
file of the destination project, or to merge resources such as strings into an existing strings.xml
file.
Instruct ADT to open the file created by the specified file
argument in Eclipse after code generation is complete.
The actual template files (resources, Java sources, Android Manifest changes) should be placed in the root/
directory, in a directory structure that roughly resembles what the output directory structure should look like.
One difference is that instead of placing source files in src/com/google/...
you can just use a naming convention like src/app_package/
to indicate that files under this directory will be placed in the destination project's source file package root.
Several functions are available to FreeMarker expressions and files beyond the standard set of built-in FreeMarker functions. These are listed below.
This function converts an activity class-like identifer string, such as FooActivity
, to a corresponding resource-friendly identifier string, such as activity_foo
.
activityClass
FooActivity
to reformat.This function converts a camel-case identifer string, such as FooBar
, to its corresponding underscore-separated identifier string, such as foo_bar
.
camelStr
FooBar
to convert to an underscore-delimited string.This function escapes a string, such as Android's
such that it can be used as an XML attribute value: Android's
. In particular, it will escape ', ", < and &.
str
This function escapes a string, such as A & B's
such that it can be used as XML text. This means it will escape < and >, but unlike escapeXmlAttribute
it will not escape ' and ". In the preceeding example, it will escape the string to A & B\s
. Note that if you plan to use the XML text as the value for a <string> resource value, you should consider using escapeXmlString
instead, since it performs additional escapes necessary for string resources.
str
This function escapes a string, such as A & B's
such that it is suitable to be inserted in a string resource file as XML text, such as A & B\s
. In addition to escaping XML characters like < and &, it also performs additional Android specific escapes, such as escaping apostrophes with a backslash, and so on.
str
Activity's Title
to escape to a proper resource XML value.This function extracts all the letters from a string, effectively removing any punctuation and whitespace characters.
str
This function converts an Android class name, such as FooActivity
or FooFragment
, to a corresponding resource-friendly identifier string, such as foo
, stripping the 'Activity' or 'Fragment' suffix. Currently stripped suffixes are listed below.
className
FooActivity
to reformat as an underscore-delimited string with suffixes removed.This function converts a resource-friendly identifer string, such as activity_foo
, to a corresponding Java class-friendly identifier string, such as FooActivity
.
resourceName
activity_foo
to reformat.This function converts a full Java package name to its corresponding directory path. For example, if the given argument is com.example.foo
, the return value will be com/example/foo
.
packageName
com.example.foo
.This function converts an underscore-delimited string, such as foo_bar
, to its corresponding camel-case string, such as FooBar
.
underStr
foo_bar
to convert to a camel-case string.When creating activity layouts, make sure to include the activity name in the root view in the layout as part of the tools
namespace, as shown in the following example:
<TextView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:text="@string/hello_world" android:padding="@dimen/padding_medium" tools:context=".${activityClass}" />
As of ADT 20 we use this attribute in layouts to maintain a mapping to the active activity to use for a layout. (Yes, there can be more than one, but this attribute is showing the activity context you want to edit the layout as. For example, it will be used to look up a theme registration (which is per-activity rather than per-layout) in the manifest file, and we will use this for other features in the future—for example to preview the action bar, which also requires us to know the activity context.