如何从里面引用的lambda? [英] How to reference a lambda from inside it?

查看:148
本文介绍了如何从里面引用的lambda?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让onCreate方法视图的高度,但我找不到任何方法来去除OnGlobalLayoutListener。

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

在Java的(工作):

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 excepting "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.

推荐答案

这里面不支持引用的lambda。

Referencing a lambda from inside it is not supported.

作为一种变通方法,您可以使用,而不是拉姆达SAM-转换为Java的功能接口匿名对象 OnGlobalLayoutListener

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

这篇关于如何从里面引用的lambda?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆