在 Retrolambda 中使用 'this' 关键字

Using 'this' keyword with Retrolambda

我对这段代码有疑问:

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();
    }
});

我想将此代码转换为使用这样的 lambda 表达式:

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();
});

但它不会工作,因为现在 this 不引用内部 class。

尝试通知参数,(this)的"complete address"。

removeGlobalOnLayoutListener(this);

像这样:

removeGlobalOnLayoutListener(MainActivity.this);

当然,您需要告知您的真实class姓名。

根据 Java specifications

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

因此,如果您需要使用 this 来引用匿名对象,则需要使用显式匿名对象,而不是 lambda。解决方法是像您的原始代码一样编写它。

Lambda 是一种在很多情况下都很有用的工具,但不需要在所有 情况下使用。