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

后端 未结 12 1449
野的像风
野的像风 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:54

    I tried this and it worked for me. Here is the Kotlin extension

    fun RecyclerView.runWhenReady(action: () -> Unit) {
        val globalLayoutListener = object: ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                action()
                viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        }
        viewTreeObserver.addOnGlobalLayoutListener(globalLayoutListener)
    }
    

    then call it

    myRecyclerView.runWhenReady {
        // Your action
    }
    

提交回复
热议问题