Android studio使用lambda表达式

   分三步


 1.引入retrolambda插件:

  在Project的build.gradle中添加

    apply plugin: 'me.tatarka.retrolambda'

   2. 设置编译选项(必须要写)

  在Project的build.gradle的android节点中添加如下代码

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

   3. 引入retrolambda的类路径,

   在Module:app的build.gradle中的buildscript->dependencies节点中添加如下代码

   classpath 'me.tatarka:gradle-retrolambda:3.2.0'
 
  
 
  
使用范例:

使用前
 
  
 
  
Observable.create(new Observable.OnSubscribe() {
    @Override
    public void call(Subscribersuper Object> subscriber) {
        Drawable drawable = ActionActivity.this.getResources().getDrawable(R.mipmap.ic_launcher);
        subscriber.onNext(drawable);
        subscriber.onCompleted();
    }
}).subscribe(new Observer() {
    @Override
    public void onNext(Object drawable) {
        img.setImageDrawable((Drawable)drawable);
    }

    @Override
    public void onCompleted() {
    }

    @Override
    public void onError(Throwable e) {
        Toast.makeText(ActionActivity.this, "Error!", Toast.LENGTH_SHORT).show();
    }
}); 
   
  

使用后
 
  
 
  
Observable.create(subscriber -> {
    Drawable drawable = ActionActivity.this.getResources().getDrawable(R.mipmap.ic_launcher);
    subscriber.onNext(drawable);
    subscriber.onCompleted();
}).subscribe(o -> img.setImageDrawable((Drawable) o), throwable -> Toast.makeText(ActionActivity.this, "Error!", Toast.LENGTH_SHORT).show(), () -> {
});

 
  

                            
                        
                    
                    
                    

你可能感兴趣的:(android)