We used lots of anonymous class in android project. For example:
new DialogInterface.OnClickListener()
new MediaPlayer.OnPreparedListener()
etc. Is there any way to replace these kinds of anonymous class using new Java lambda expression?
You can only replace anon classes for functional interfaces. Lambda expression requires a functional interface i.e. interface that contains only single method.
You have to
enable jack in your app's gradle:
'defaultConfig { ... jackOptions { enabled true } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } }'
now you can replace your anonymous class with lambda expression. for example: replace
mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onSomethingClicked();
}
});
to
mView.setOnClickListener(view -> onSomethingClicked())
It is important to keep in mind that enabling jack still generates anonymous classes during the compile step. So, be careful about all the leaks you can have with anonymous classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With