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

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

    I improved the answer of android developer to fix this problem. It's a Kotlin code but should be simple to understand even if you know only Java.

    I wrote a subclass of LinearLayoutManager which lets you listen to the onLayoutCompleted() event:

    /**
     * This class calls [mCallback] (instance of [OnLayoutCompleteCallback]) when all layout
     * calculations are complete, e.g. following a call to
     * [RecyclerView.Adapter.notifyDataSetChanged()] (or related methods).
     *
     * In a paginated listing, we will decide if load more needs to be called in the said callback.
     */
    class NotifyingLinearLayoutManager(context: Context) : LinearLayoutManager(context, VERTICAL, false) {
        var mCallback: OnLayoutCompleteCallback? = null
    
        override fun onLayoutCompleted(state: RecyclerView.State?) {
            super.onLayoutCompleted(state)
            mCallback?.onLayoutComplete()
        }
    
        fun isLastItemCompletelyVisible() = findLastCompletelyVisibleItemPosition() == itemCount - 1
    
        interface OnLayoutCompleteCallback {
            fun onLayoutComplete()
        }
    }
    

    Now I set the mCallback like below:

    
    mLayoutManager.mCallback = object : NotifyingLinearLayoutManager.OnLayoutCompleteCallback {
        override fun onLayoutComplete() {
            // here we know that the view has been updated.
            // now you can execute your code here
        }
    }
    
    

    Note: what is different from the linked answer is that I use onLayoutComplete() which is only invoked once, as the docs say:

    void onLayoutCompleted (RecyclerView.State state)

    Called after a full layout calculation is finished. The layout calculation may include multiple onLayoutChildren(Recycler, State) calls due to animations or layout measurement but it will include only one onLayoutCompleted(State) call. This method will be called at the end of layout(int, int, int, int) call.

    This is a good place for the LayoutManager to do some cleanup like pending scroll position, saved state etc.

提交回复
热议问题