Pamir Cevikogullari Pamir Cevikogullari - 3 months ago 15
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() {
@Override
public void onGlobalLayout() {
containerLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int width = layout.getMeasuredWidth();
int height = layout.getMeasuredHeight();

}
});


In Kotlin (not accepting "this"):

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


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

Answer

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