Pamir Cevikogullari Pamir Cevikogullari - 2 months ago 11
Android Question

How to reference a lambda from inside it?

I am trying to get height of a view in onCreate method but I couldn't find any way to remove OnGlobalLayoutListener.

In Java (working):

containerLayout.getViewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
public void onGlobalLayout() {
int width = layout.getMeasuredWidth();
int height = layout.getMeasuredHeight();


In Kotlin (not accepting "this"):

containerLayout.viewTreeObserver.addOnGlobalLayoutListener {
Toast.makeText(applicationContext, "size is "+ containerLayout.height,Toast.LENGTH_LONG).show()

Is there any reference or example for this problem? Thanks.


Referencing a lambda from inside it is not supported.

As a workaround, you might use anonymous object instead of lambda SAM-converted to Java functional interface OnGlobalLayoutListener:

containerLayout.viewTreeObserver.addOnGlobalLayoutListener(object: OnGlobalLayoutListener {
    override fun onGlobalLayout() {
        // your code here. `this` should work