1

I have a problem with this code:

view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
            view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        } else {
            //noinspection deprecation
            view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        }
        getDefaultIntent();
    }
});

I want to convert this code to use a lambda expression like this:

view.getViewTreeObserver().addOnGlobalLayoutListener(()->{
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
        view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
    } else {
        //noinspection deprecation
        view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
    }
    getDefaultIntent();
});

But it wont work because now this doesn't refer to the inner class.

spenibus
  • 4,339
  • 11
  • 26
  • 35
Abdelrhman Talat
  • 1,205
  • 2
  • 13
  • 25

2 Answers2

0

try inform to parameter, the "complete address" of (this).

removeGlobalOnLayoutListener(this);

Like these:

removeGlobalOnLayoutListener(MainActivity.this);

of course, that you need inform your real class name.

0

Per the Java specifications,

The value denoted by this in a lambda body is the same as the value denoted by this in the surrounding context.

As such, if you need to use this to refer to the anonymous object, you need to use an explicit anonymous object, not a lambda. The work around is writing it like your original code.

Lambda's are a tool that are useful in lots of situations, but do not need to be used in all situations.

iagreen
  • 31,470
  • 8
  • 76
  • 90