Android開發技巧 (五) —— Lambda表達式

Lambda表達式本質是一種匿名方法,它既沒有方法名,也沒有訪問修飾符和返回值類型,用它來寫代碼更簡潔,更易懂。

Lambda是Java8的新特性,所以要在app/build.gardle中添加:

android {
......
    compileOptions{
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

之後就可以使用Lambda表達式了,像下面這樣兩種方法相同:

        new Thread(new Runnable() {
            @Override
            public void run() {
                // 具體邏輯
            }
        }).start();
        
        new Thread(() -> {
            // 具體邏輯
        }).start();

爲啥可以有這麼精簡的寫法呢?這是因爲Thread類的構造函數接收的參數是一個Runnable接口,並且該接口中只有一個待實現的方法:

@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

像是這種只有一個待實現方法的接口,都可用Lambda表達式的寫法。
瞭解了這種基本寫法罵我們接着嘗試自定義一個接口。然後用Lambda表達式的方式實現,新建一個MyListener接口,代碼如下所示:

public interface MyListener{
	String doSomething(String a, int b);
}

那麼就可以這麼實現它:

MyListener listener = (String a, int b) -> {
	String result = a + b;
	return result;
};

而且 Java 能自動推斷出Lambda表達式的參數類型,所以還能這麼寫:

MyListener listener = (a, b) -> {
	return a + b;
}

再舉個具體的例子,比方說現在有一個方法是接收MyListener參數:

public void hello(MyListener listener){
	String a = "Hello Lamba";
	int b = 1024;
	String result  = listener.dosomething(a, b);
	Log.d(TAG, result);
}

在調用hello()就能這麼寫:

hello((a, b) -> {
	String result = a + b;
	return result;
});

那麼在Android中哪些方法能替換呢?
按鈕點擊事件
原來:

Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener(){
	@Override
	public void onClick(View v){
		// 處理點擊事件
	}
));

Lambda簡化:

Button button = findViewById(R.id.button);
button.setOnClickListener(v -> {
	// 處理點擊事件
});

搞定!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章