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 onClickfindViewById(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
}
}
This content is copyright and owned by https://webdeveloperpadawan.blogspot.com/
No comments:
Post a Comment