Using the Retrolambda library. This tutorial explains the usage of the Retrolambda library.

1. Retrolambda

Retrolambda is a library which allows to use Java 8 lambda expressions, method references and try-with-resources statements on Java 7, 6 or 5.

The Gradle Retrolambda Plug-in allows to integrate Retrolambda into a Gradle based build. This allows for example to use these constructs in an Android application, as standard Android development currently does not yet support Java 8.

2. Exercise: Using Retrolambda in your Android project

2.1. Create project

Create a new Android project with the top level project name com.vogella.android.retrolambda. Add a button to the existing layout with the @+id/button" ID.

2.2. Add Retrolambda to your Gradle build configuratoin

Add the me.tatarka:gradle-retrolambda plug-in as dependency to your build.gradle file.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.4.0'
        classpath 'me.tatarka:gradle-retrolambda:3.2.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

Add the source and target compatibility to Java 8 and apply the new plug-in in your app/build.gradle file.

apply plugin: 'com.android.application'
apply plugin: 'me.tatarka.retrolambda'

android {
    compileSdkVersion 22
    buildToolsVersion "23.0.0 rc2"

    defaultConfig {
        applicationId "com.vogella.android.retrolambda"
        minSdkVersion 22
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}



dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
}

2.3. Validate setup by using a lambda expressions

Using the lambda configuration by using it with your button to show a Toast once the button is clicked.

package com.vogella.android.retrolambda;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button view = (Button) findViewById(R.id.button);
        view.setOnClickListener(e-> Toast.makeText(this,"Hello", Toast.LENGTH_LONG).show());
    }
}

3. Retrofit resources