尝试在onCreate方法中获取视图的高度,但找不到任何方法来删除OnGlobalLayoutListener。
在java中这么写是OK的:
containerLayout.getViewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
containerLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int width = layout.getMeasuredWidth();
int height = layout.getMeasuredHeight();
}
});
在kotlin中,使用lambda表达式,无法获取到this,而无法删除掉这个内部类的listener:
containerLayout.viewTreeObserver.addOnGlobalLayoutListener {
containerLayout.viewTreeObserver.removeOnGlobalLayoutListener(this)
Toast.makeText(applicationContext, "size is "+ containerLayout.height,Toast.LENGTH_LONG).show()
}
kotlin是不支持从内部引用lambda,解决方法是,可以使用匿名对象,而不是将lambda SAM转换为Java功能接口OnGlobalLayoutListener:
containerLayout.viewTreeObserver.addOnGlobalLayoutListener(object: ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
// your code here. `this` should work
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
viewTreeObserver.removeOnGlobalLayoutListener(this)
} else {
viewTreeObserver.removeGlobalOnLayoutListener(this)
}
}
})