我们在开发java代码时,会经常遇到一些事件处理,比如 某个控件的点击,
1:事件处理:比如
basic_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int a = 10; int b = a+ 20; Log.i("aa",b+"a");}});
其实对于这个匿名类部类的lambda写法,只需要一句话,如下
basic_btn.setOnClickListener( n -> {
//to do
});
2:list处理
List lists = Arrays.asList("adfa","asdf");
for(String list : lists){
Log.d("aa",list);
}
经过lambda写法,打印遍历:
lists.forEach(n -> { //**});
当然,对于lambda还有很多用法,可以继续深入研究。
当然如果要使用lambda语法,需要再android工程中进行过配置,
在build.gradle哦中添加支持java8
apply plugin: 'com.android.application'
//lambda
apply plugin: 'me.tatarka.retrolambda'
android {
dataBinding {
enabled = true
}
compileSdkVersion 25
buildToolsVersion '25.0.2'
defaultConfig {
applicationId "com.zx.databindingdemo"
minSdkVersion 17
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
/*jackOptions {
enabled true
}*/
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
//需要支持java8
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
/*androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})*/
//compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
//testCompile 'junit:junit:4.12'
}
主工程:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
//lambda
classpath 'me.tatarka:gradle-retrolambda:3.2.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
只有这样才能运行,否则各种错误。