Use Lambda expressions in Android Studio, androidlambda

Source: Internet
Author: User

Use Lambda expressions in Android Studio, androidlambda

Lambda expressions are a function-based derivation language supported by JDK 8, which can greatly reduce the redundant code of anonymous internal classes. In Android, you can use it extensively in scenarios such as setting listeners and setting asynchronous callbacks.

Currently, Android development has gradually migrated from the Eclipse ADT to Android Studio. However, the current version of Android Studio does not directly support Lambda expressions and requires plug-ins. Of course, JDK 8 or a later version is required ).

1. Introduce the plugin Lambda plug-in:

Add

apply plugin: 'me.tatarka.retrolambda'

2. Set the compilation option (or you may not write it)

Add the following code to the Project's build. gradle android node:

compileOptions {        sourceCompatibility JavaVersion.VERSION_1_8        targetCompatibility JavaVersion.VERSION_1_8    }

3. Introduce the ingress Lambda class path and add the following code to the buildscript> dependencies node in Module: app build. gradle.

classpath 'me.tatarka:gradle-retrolambda:3.2.0'

4. build. gradle

5. Write the test code as follows:

    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        textView = (TextView)findViewById(R.id.text);        textView.setOnClickListener( v -> Toast.makeText(getApplicationContext(), "Lambda", Toast.LENGTH_LONG).show());    }

6. Run the command to check whether it is normal.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.