Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting OnCheckedChangeListener with a Lambda

I want to use a lambda rather than an anonymous class for OnCheckedChangeListener.

The original code for setting the listener works fine and reads:

mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
        mCrime.setSolved(isChecked);
    }
});

I tried changing it to a lambda by doing:

mCheckBox.setOnCheckedChangeListener(l -> mCrime.setSolved(isChecked));

but I receive an error from Android Studio saying: cannot resolve symbol is checked.

I had thought a lambda would resolve isChecked implicitly even though the onCheckChanged takes two arguments. What is wrong with my understanding?

like image 566
Neal Avatar asked Oct 17 '18 16:10

Neal


People also ask

Can be replaced with lambda in Android Studio?

If you want to replace all the lambda expression from the project you can try Ctrl + Shift+ Alt + I on inspection search tab, search anonymous type can be replaced with lambda. It will replace all the anonymous type to lambda. With Studio 3.5.

Are lambdas more efficient?

Generally speaking, lambdas and streams provide a more concise and (once everyone is up to speed) more readable way of expressing this kind of algorithm.

What is Lambda How does it improve help in implementation?

It helps to iterate, filter and extract data from collection. The Lambda expression is used to provide the implementation of an interface which has functional interface. It saves a lot of code. In case of lambda expression, we don't need to define the method again for providing the implementation.


2 Answers

Your syntax is wrong. What you have shouldn't even compile. Use this:

mCheckBox.setOnCheckedChangeListener((view, isChecked) -> mCrime.setSolved(isChecked));

The stuff before the -> doesn't represent the listener, but rather the arguments that are passed in that listener, in this case a View and a boolean.

like image 172
TheWanderer Avatar answered Oct 19 '22 14:10

TheWanderer


isChecked is just a parameter name it is not there when you are using lambdas how ever here is the correct lambda with the parameter names for your onCheckChangeListener

mCheckBox.setOnCheckedChangeListener((CompoundButton.OnCheckedChangeListener) (buttonView, isChecked) -> mCrime.setSolved(isChecked)); 
like image 29
SamHoque Avatar answered Oct 19 '22 13:10

SamHoque