2017年1月7日 星期六

在 Android Studio 中使用 Java 8 Lamda ---- Retrolambda Plugin

Android 目前只有 7.0 以上支援JVM8.0,因此在舊版系統中,必須使用插件來轉換
如此一來便能使用匿名表達方式Lambda來撰寫程式
ref link
retrolambda https://github.com/orfjackal/retrolambda
gradle-retrolambda https://github.com/evant/gradle-retrolambda
以下兩種情況使用Lambda簡化

元件的OnClickListener
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//未使用 lambda
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("click")
}
});
//使用 lambda
button.setOnClickListener(view -> {
System.out.println("click")
});
//還可以更簡化
button.setOnClickListener(view -> System.out.println("click"));
Thread的Runnable
1
2
3
4
5
6
7
8
9
10
//未使用 lambda
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("run");
}
});
//使用 lambda
new Thread(() -> System.out.println("run"));

lambda 語法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
input -> body
view -> System.out.println("click")
//intput 種類
//無輸入 void
() -> body
//單個輸入
x -> System.out.println(x)
//多個輸入
(x, y) -> x + y;
//不省略型別
(int x, int y) -> x + y;
//body 種類
//什麼都不做
() -> {}
//單行不回傳,單行可省略{}
(x, y) -> x + y;
//單行回傳
(x, y) -> x + y
//多行不回傳
(x, y) ->{
x * x;
y * y;
}
//多行回傳
(x, y) ->{
x * x;
y * y;
return x + y;
}


安裝方式


修改app/build.gradle
在最後添加下面幾行
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'me.tatarka:gradle-retrolambda:3.4.0'
}
}
// Required because retrolambda is on maven central
repositories {
mavenCentral()
}
apply plugin: 'com.android.application' //or apply plugin: 'java'
apply plugin: 'me.tatarka.retrolambda'
最後將Compile JDK改為1.8
1
2
3
4
compileOptions {
targetCompatibility JavaVersion.VERSION_1_8
sourceCompatibility JavaVersion.VERSION_1_8
}

沒有留言 :

張貼留言