Android development skills (five) - Lambda Expressions

Lambda expressions is essentially an anonymous method, it has neither the method name, and no access modifiers and return type, use it to write code more concise and easy to understand.

Lambda is a new feature Java8, so you want to app/build.gardleadd in:

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

Then you can use Lambda expressions, and like the same two methods below:

        new Thread(new Runnable() {
            @Override
            public void run() {
                // 具体逻辑
            }
        }).start();
        
        new Thread(() -> {
            // 具体逻辑
        }).start();

There are so why can streamline the wording of it? This is because the Threadconstructor for the class is a received parameter Runnableinterface, and this interface is only one way to be achieved:

@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();
}

This is only one to be like interface methods are available Lambdawritten expression.
This basic understanding of written and then try to blame us for a custom interface. Then Lambdaways to achieve expression, a new MyListenerinterface code as follows:

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

So then you can achieve it:

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

And Javacan automatically infer the Lambdaparameter type of the expression, you can write:

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

As another specific example, say there are a method of receiving MyListener parameters:

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

The call hello()will be able to write:

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

So what method can replace it in Android?
Button click event
of the original:

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

Lambdasimplify:

Button button = findViewById(R.id.button);
button.setOnClickListener(v -> {
	// 处理点击事件
});

Get!

Published 180 original articles · won praise 16 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_41205771/article/details/104464725