kotlin for Andrid

1. OnGlobalLayoutListener

Use kotlin to reduce OnGlobalLayoutListener boilerplate code and make the code look more awesome

traditional java writing

recycler.viewTreeObserver.addOnGlobalLayoutListener(
    object : ViewTreeObserver.OnGlobalLayoutListener {
    
    
        override fun onGlobalLayout() {
    
    
            recycler.viewTreeObserver.removeOnGlobalLayoutListener(this);
            // do whatever
        }
   });

kotlin writing

Define an extension function for View

inline fun View.waitForLayout(crossinline f: () -> Unit) {
    
    
    with(viewTreeObserver) {
    
    
        addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
    
    
            override fun onGlobalLayout() {
    
    
                removeOnGlobalLayoutListener(this)
                f()
            }
        })
    }
}

use

view.waitForLayout {
    
    
	// do whatever
}

Guess you like

Origin blog.csdn.net/H_Zhang/article/details/116525175