2016-06-29 18 views
2

我有以下擴展方法。我如何參考傳入addOnGLobalLayoutListener()方法的OnGlobalLayoutListener?我需要將聽衆傳遞給removeOnGlobalLayoutListener()方法。如何引用Kotlin中的匿名內部類?

fun View.OnGlobalLayout(callback:() -> Unit): Unit{ 
    this.viewTreeObserver.addOnGlobalLayoutListener { 
     if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) { 
      this.viewTreeObserver.removeOnGlobalLayoutListener(this); 
     } 
     else { 
      this.viewTreeObserver.removeGlobalOnLayoutListener(this); 
     } 
     callback(); 
    } 
} 
+1

參見http://stackoverflow.com/questions/38074356/kotlin-recommended-way-of-unregistering-a章24 -listener上帶有一個-SAM – yole

回答

2

一種方法是使用object expression而不是lambda像這樣:

fun View.OnGlobalLayout(callback:() -> Unit): Unit { 
    val viewTreeObserver = this.viewTreeObserver 
    viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { 
     override fun onGlobalLayout() { 
      if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) { 
       viewTreeObserver.removeOnGlobalLayoutListener(this); 
      } else { 
       viewTreeObserver.removeGlobalOnLayoutListener(this); 
      } 
      callback(); 
     } 
    }) 
}