30 May 2016

Android Lambda

I've heard a lot about lambda recently and how amazing Java 8 is. I'm not really sure this will have a huge impact on Android as I fail to see the relevance, none the less I was interested and keen to experiment.

I thought I'd create a super simple example by changing the OnClickListener of a button and trying to replace it with a lambda. Nothing shocking here, just wanted to know if I could. So I created a brand new project and here's how I got it working.

Before we go any further you'll need to:

  • Donwload the Android N SDK, 
  • Download JDK 1.8 (and target it with Android Studio) 
  • You'll need an emulator or device capable of running Android N.

Android N

To use lambdas we have to target Android N so I've updated the compile version, build tools, min Sdk and target Sdk.

android {
    compileSdkVersion 'android-N'
    buildToolsVersion '24.0.0-rc3'

    defaultConfig {
        applicationId "eightest.test.com.eighttest"
        minSdkVersion 'N'
        targetSdkVersion 'N'
        versionCode 1
        versionName "1.0"
    }

The code

This is what we would normally do for a onClick
findViewById(R.id.activity_main_text).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        showToast()
    }
});

This is how a lambda makes it look a little cleaner
findViewById(R.id.activity_main_text).setOnClickListener((View v) -> {showToast();});

Target Java 8

We need to specifically target java 8 (do this inside the Android brackets, after buildTypes)
    compileOptions {
        targetCompatibility 1.8
        sourceCompatibility 1.8
    }

Utilise Jack compiler

Now we need to tell Android to use the Jack compiler which will allow us to utilise Java 8.
    defaultConfig {
        applicationId "eightest.test.com.eighttest"
        minSdkVersion 'N'
        targetSdkVersion 'N'
        versionCode 1
        versionName "1.0"
        jackOptions {
            enabled true
        }
    }

No comments: