Home > Net >  Why is View addOnGlobalLayoutListener not calling when I migrate to Kotlin extensions?
Why is View addOnGlobalLayoutListener not calling when I migrate to Kotlin extensions?

Time:08-30

I am trying to migrate my Java class function to Kotlin extension function. The function calls addOnGlobalLayoutListener which registers a callback to be invoked when the global layout state or the visibility of views within the view tree changes. This is my Java function working normally as UtilClass.viewTreeObserverCheck(target) {}

public static final void viewTreeObserverCheck(View target, CustomVoidClosure function) {
        if (target.getViewTreeObserver().isAlive()) {
            // callback to be invoked when the global layout state or the visibility of views within the view tree changes
            target.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    target.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    function.invoke();
                }
            });
        }
    }

I have migrated to Kotlin View extension below. This does not call as view.treeObserverCheck {}

fun View.treeObserverCheck(closure: () -> Unit) {
    if (this.viewTreeObserver.isAlive) {
        // callback to be invoked when the global layout state or the visibility of views within the view tree changes
        this.viewTreeObserver.addOnGlobalLayoutListener {
            object : ViewTreeObserver.OnGlobalLayoutListener {
                override fun onGlobalLayout() {
                    viewTreeObserver.removeOnGlobalLayoutListener(this)
                    closure.invoke()
                }
            }
        }
    }
}

CodePudding user response:

fun View.treeObserverCheck(closure: () -> Unit) {
    if (this.viewTreeObserver.isAlive) {
        this.viewTreeObserver.addOnGlobalLayoutListener (
            object : ViewTreeObserver.OnGlobalLayoutListener {
                override fun onGlobalLayout() {
                    viewTreeObserver.removeOnGlobalLayoutListener(this)
                    closure.invoke()
                }
            }
        )
    }
}

you have used flower brackets instead of round brackets [line no 3]

enter image description here

  • Related