Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace anonymous class using lambda expression android

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?

like image 397
0xAliHn Avatar asked Jul 14 '26 06:07

0xAliHn


1 Answers

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

  1. enable jack in your app's gradle:

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

  2. 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.

like image 56
Krupal Shah Avatar answered Jul 18 '26 04:07

Krupal Shah