2015-09-26 64 views
1

我有這個代碼的問題:使用「這個」關鍵字與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沒有引用內部類。

+0

你是對的。它不會工作。 「這個」總是指周圍的範圍,從來沒有lambda本身 – iagreen

+0

@iagreen是他們的解決方法嗎? –

回答

0

Java specifications

通過this在一個lambda體所表示的值是與由this在周圍的上下文表示的值 。

因此,如果你需要使用this來引用匿名對象,你需要使用一個明確的匿名對象,而不是一個拉姆達。解決方法是將它寫成像原始代碼一樣。

Lambda的工具在很多情況下都很有用,但不需要在全部的情況下使用。

0

嘗試通知參數「(完成地址)」(this)。

removeGlobalOnLayoutListener(this); 

像這些:

removeGlobalOnLayoutListener(MainActivity.this); 
當然

,你需要告知你的真實的類名。

+0

removeGlobalOnLayoutListener() 以ViewTreeObserver.OnGlobalLayoutListener作爲參數而不是活動 –