我试图在onCreate方法中获得视图的高度,但我找不到任何方法删除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(); 

    }  
});

在Kotlin (不接受"这个"):

   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.

推荐答案

Referencing a lambda from inside it is not supported.

作为一种解决方法,您可以使用匿名对象,而不是转换为Java functional interface OnGlobalLayoutListener的lambda SAM:

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

Kotlin相关问答推荐

调用即发即忘方法--哪个作用域?

Spring Boot Bean验证器未触发

计算值的Elvis算子

在Jetpack Compose中创建波浪式文本动画:顺序中断问题

如何在Android应用判断上运行多个查询

在协程上下文中重新抛出异常

MyType.()在 Kotlin 中是什么意思?

有什么方法可以要求在 kotlin 中的类型参数上进行注释?

使用启动或使用 coroutineScope 启动协程之间的区别

将 Integer 转换为 Unit 编译成功

将 SharedPreferences 中的值公开为流

如何将glide显示的图像下载到设备存储中.Kotlin

如何在 kotlin 中通过反射设置委托属性值?

类型是什么意

无法删除部分子项.这可能是因为进程打开了文件或将其工作目录设置在目标目录中

ActivityOptions.makeSceneTransitionAnimation 在具有多个视图的 kotlin 中不起作用

Kotlin 的 Double.toInt() 中使用了哪种方法,舍入还是截断?

Kotlin协程无法处理异常

Kotlin中的函数接口

Kotlin:获取文件的扩展名,例如.txt