在Android Studio中使用Lambda運算式

來源:互聯網
上載者:User

標籤:UI   public   from   toast   class   array   eof   ide   ...   

Lambda運算式是Java 8的一個新特性,可以替代只有一個函數的介面實現,告別匿名內部類,代碼看起來更簡潔易懂。Lambda運算式同時還提升了對集合的迭代、遍曆、過濾資料的操作。那麼在Android Studio中如何使用lambda運算式呢?

 

項目使用的jdk要為jdk 8或更高版本

 

修改build.gradle檔案,enable jack和設定sourceCompatibility,targetCompatibility為jdk 8

defaultConfig {  ... jackOptions { enabled=true } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 }

 

 然後在項目中就可以愉快使用lambda運算式了,大家感受下:

public class TestActivity extends BaseActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.test);        findViewById(R.id.button1).setOnClickListener(view -> onButton1());        findViewById(R.id.button2).setOnClickListener(view -> onButton2());    }    public void onButton1() {        Runnable runnable = () -> Toast.makeText(this, "abcd", Toast.LENGTH_SHORT).show();        runnable.run();    }    public void onButton2() {        Observable.from(Arrays.asList(1, 2, 3, 4, 5))                .filter(integer -> integer % 2 == 0)                .map(integer -> integer * integer)                .subscribeOn(Schedulers.io())                .observeOn(AndroidSchedulers.mainThread())                .subscribe(integer -> Toast.makeText(this, String.valueOf(integer), Toast.LENGTH_SHORT).show());    }}

 

在Android Studio中使用Lambda運算式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.