首页 > 代码库 > jdk 8 lambda表达式 及在Android Studio的使用示例

jdk 8 lambda表达式 及在Android Studio的使用示例

以前觉得java让人觉得有趣的一个特点是支持:匿名内部类,而最近发现jdk8已支持lambda并有更简便的方式,来实现匿名内部类. 这会让程序员更舒服,更喜欢java. 多年前觉得java语法和C#语法差得有点远,没有C#那么写来方便,现在觉得jdk8也很不错了。做技术还是要向前看。

final TextView txtView2 = (TextView)this.findViewById(R.id.txtView2);Button btnChangeView = (Button)findViewById(R.id.btnChangeText);btnChangeView.setOnClickListener(new View.OnClickListener() {    @Override    public void onClick(View v) {        txtView2.setText("Text 改变");    }});

新的实现方式:

final TextView txtView2 = (TextView)this.findViewById(R.id.txtView2);Button btnChangeView = (Button)findViewById(R.id.btnChangeText);//btnChangeView.setOnClickListener(e -> Log.i("MyTag", "Button Clicked.") );assert btnChangeView != null;btnChangeView.setOnClickListener((view) -> {    Log.i(TAG, "btnChangeView Clicked:" + view.getId());    txtView2.setText("Text 改变:" + new Date().toString());});

 

参考:

http://stackoverflow.com/questions/37004069/errorjack-is-required-to-support-java-8-language-features

http://www.jianshu.com/p/5fc2b3362702

需要更改配置: build.gradle

defaultConfig {  ...    jackOptions {      enabled true    }  }  compileOptions {    sourceCompatibility JavaVersion.VERSION_1_8    targetCompatibility JavaVersion.VERSION_1_8  }
apply plugin: ‘com.android.application‘android {    compileSdkVersion 23    buildToolsVersion "24.0.2"    defaultConfig {        applicationId "com.firstapp.test.firstapp"        minSdkVersion 16        targetSdkVersion 23        versionCode 1        versionName "1.0"        jackOptions {            enabled true        }    }    buildTypes {        release {            minifyEnabled false            proguardFiles getDefaultProguardFile(‘proguard-android.txt‘), ‘proguard-rules.pro‘        }    }    compileOptions {        sourceCompatibility 1.8        targetCompatibility 1.8    }}dependencies {    compile fileTree(include: [‘*.jar‘], dir: ‘libs‘)    testCompile ‘junit:junit:4.12‘    compile ‘com.android.support:appcompat-v7:23.4.0‘}

 

jdk 8 lambda表达式 及在Android Studio的使用示例