Use Lambda expressions in Android
Android Studio reports an error by default when using a Lambda expression. Even if you are using java 8, to use a lambda expression in android studio, we must use a plug-in called Lambda, this plug-in is compatible with the lambda expression feature in java 8 to java 5. It is also easy to use.
First, add build. gradle in the root directory of the project.
classpath 'me.tatarka:gradle-retrolambda:3.2.0'
Eventually the entire file will look like this
buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:1.2.3' classpath 'me.tatarka:gradle-retrolambda:3.2.0' }}allprojects { repositories { jcenter() }}
Then use the plug-in build. gradle under the module Directory to add
apply plugin: 'me.tatarka.retrolambda'
And add
compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 }
Eventually the entire file is like this.
apply plugin: 'com.android.application'apply plugin: 'me.tatarka.retrolambda'android { compileSdkVersion 22 buildToolsVersion 22.0.1 defaultConfig { applicationId cn.edu.zafu.rxdemo minSdkVersion 15 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 { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:22.2.0'}
Now, let's try the lambda expression and experiment with the View click event.
This is the case before using lambda expressions.
btn = (Button) findViewById(R.id.btn);btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), test, Toast.LENGTH_LONG).show() }});
This is the case after lambda expressions are used.
btn = (Button) findViewById(R.id.btn);btn.setOnClickListener(v -> Toast.makeText(getApplicationContext(), test, Toast.LENGTH_LONG).show());
Okay. Run the project. If Toast is displayed by clicking the button, it indicates that you have succeeded. But if you run the ClassNotFound error, clean the project and compile and run it.
Have you found that the code is much simpler. This article is the first blog post on the road to learning RxJava (RxAndroid). After all, RxJava uses a lot of lambda expression features. Although you do not need lambda expressions, the code is very simplified after lambda expressions are used.