Creating Android Application with Groovy

23 / Jul / 2015 by Simranjit Kour 1 comments

Groovy 2.4 was released in January 2015, with native support for Android development. It allows to write Android applications fully using Groovy.

Running Groovy on Android

Step 1: Create a new Android project in Android Studio

Step 2: Open this build.gradle (Module: app) file:
Insert the following code before the first line:

buildscript {
        repositories {
        dependencies {
            classpath ''
            classpath 'org.codehaus.groovy:gradle-groovy-android-plugin:0.3.6'

Insert the following code after the “apply plugin:’'” line:

apply plugin: 'groovyx.grooid.groovy-android'

Finally, near the end of the gradle script, insert a line in dependencies:

compile 'org.codehaus.groovy:groovy:2.4.1:grooid'

After changing the gradle file, gradle needs to be “sync”ed.

Step 3: You will now create an additional “Java Folder” below main. Use New->Folder->Java Folder instead of New->Directory
The name in the entry field is src/main/groovy.
Note: Groovy code files need to be placed in src/main/groovy instead of src/main/java. Adding Groovy files to src/main/java will not work!

Step 4: Create a new, MainActivity, with the context menu of the groovy folder, and enter the name of this class fully qualified with the package name.

Step 5: MainActivity class can be migrated from .java to .groovy by choosing Refactor->Rename File from the context menu. The file extension .java is simply replaced with a .groovy extension.

Step 6: Give the “Hello World” text view an id in the res/layout/activity_main.xml file, like this:


Step 7: In MainActivity.groovy, programmatically change the text shown by this view using groovy’s string interpolation:

public class MainActivity extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
        int id =
        findViewById(id).text = "Hello Groovy"

Step 8: Build and execute the application.

It is very easy to run Groovy on Android. Because of Groovy’s interoperability with Java, it is also very easy to mix Groovy and Java in the same application.

Happy groovy’ing!


comments (1 “Creating Android Application with Groovy”)

Leave a comment -