Skip to content

Instantly share code, notes, and snippets.

@patrickhammond
Last active August 29, 2015 14:05
Show Gist options
  • Select an option

  • Save patrickhammond/13750cd9ce8a11374616 to your computer and use it in GitHub Desktop.

Select an option

Save patrickhammond/13750cd9ce8a11374616 to your computer and use it in GitHub Desktop.
Lambdas on Android...its a brave new world. See: https://github.com/evant/gradle-retrolambda
// Uninteresting parts removed for clarity
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'me.tatarka:gradle-retrolambda:2.2.3'
}
}
repositories {
mavenCentral()
}
apply plugin: 'com.android.application'
apply plugin: 'retrolambda'
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
// Old school
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MyActivity.this, "Hello", Toast.LENGTH_SHORT).show();
}
});
// Verbose lambda expression
button.setOnClickListener((View) -> {
Toast.makeText(this, "Hello", Toast.LENGTH_SHORT).show();
});
// Terse lambda expression
button.setOnClickListener((View) -> Toast.makeText(this, "Hello", Toast.LENGTH_SHORT).show());
// Method references
button.setOnClickListener(this::handleButtonClick);
}
private void handleButtonClick(View view) {
Toast.makeText(this, "Hello", Toast.LENGTH_SHORT).show();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment