How to know when the RecyclerView has finished laying down the items?

后端 未结 12 1472
野的像风
野的像风 2020-11-29 20:06

I have a RecyclerView that is inside a CardView. The CardView has a height of 500dp, but I want to shorten this height if the Re

12条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 20:44

    If you use Kotlin, then there is a more compact solution. Sample from here.
    This layout listener is usually used to do something after a View is measured, so you typically would need to wait until width and height are greater than 0.
    ... it can be used by any object that extends View and also be able to access to all its specific functions and properties from the listener.

    // define 'afterMeasured' layout listener:
    inline fun  T.afterMeasured(crossinline f: T.() -> Unit) {
        viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                if (measuredWidth > 0 && measuredHeight > 0) {
                    viewTreeObserver.removeOnGlobalLayoutListener(this)
                    f()
                }
            }
        })
    }
    
    // using 'afterMeasured' handler:
    myRecycler.afterMeasured {
        // do the scroll (you can use the RecyclerView functions and properties directly)
        // ...
    }    
    

提交回复
热议问题