Android Studio defaults to using lambda expressions, and even if you're using Java 8, in order to use lambda expressions in Android Studio, we have to rely on a plug-in Retrolambda, which will Java The lambda expression attribute in 8 is compatible with Java 5. It's also easy to use.
First add the Build.gradle in the project root directory
‘me.tatarka:gradle-retrolambda:3.2.0‘
Eventually the whole file will look like this.
{ repositories { jcenter() } { classpath ‘com.android.tools.build:gradle:1.2.3‘ classpath ‘me.tatarka:gradle-retrolambda:3.2.0‘ }{ repositories { jcenter() }}
Then use the plugin in Build.gradle in the module directory to add
‘me.tatarka.retrolambda‘
and join under Android node
compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 }
Eventually the whole file is like this.
Apply plugin:' Com.android.application 'Apply plugin:' Me.tatarka.retrolambda 'Android {Compilesdkversion ABuildtoolsversion"22.0.1"Defaultconfig {ApplicationID"Cn.edu.zafu.rxdemo"Minsdkversion theTargetsdkversion AVersioncode1Versionname"1.0"} buildtypes {release {minifyenabledfalseProguardfiles Getdefaultproguardfile (' Proguard-android.txt '),' Proguard-rules.pro '}} compileoptions {SourceCompatibility Javaversion.version_1_8 targetcompatibility javaversion.version_1_8}}dependencies {compile fi Letree (dir:' Libs ', include: [' *.jar ']) Compile' com.android.support:appcompat-v7:22.2.0 '}
Now let's try the lambda expression and experiment with the Click event of the view.
This is the case before using a lambda expression
btn = (Button) findViewById(R.id.btn);btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText"test", Toast.LENGTH_LONG).show() }});
This is the case after using a lambda expression.
btn = (Button) findViewById(R.id.btn);btn.setOnClickListener(v -> Toast.makeText"test", Toast.LENGTH_LONG).show());
OK, run the project, if you click on the button, the toast indicates that you succeeded, but if you run a classnotfound error, clean the project, then compile and run, and it will run successfully.
How about that there is no code that has been streamlined a lot. This article is the first blog post to begin the learning path of Rxjava (rxandroid), after all, Rxjava use lambda expression features extensively. Although you can also use lambda expressions, using a lambda expression will make the code very thin.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Using lambda expressions in Android