How to implement endless list with RecyclerView?

前端 未结 30 3143
无人及你
无人及你 2020-11-22 02:22

I would like to change ListView to RecyclerView. I want to use the onScroll of the OnScrollListener in RecyclerView to determine if a

30条回答
  •  暖寄归人
    2020-11-22 03:00

    With the power of Kotlin's extension functions, the code can look a lot more elegant. Put this anywhere you want (I have it inside an ExtensionFunctions.kt file):

    /**
     * WARNING: This assumes the layout manager is a LinearLayoutManager
     */
    fun RecyclerView.addOnScrolledToEnd(onScrolledToEnd: () -> Unit){
    
        this.addOnScrollListener(object: RecyclerView.OnScrollListener(){
    
            private val VISIBLE_THRESHOLD = 5
    
            private var loading = true
            private var previousTotal = 0
    
            override fun onScrollStateChanged(recyclerView: RecyclerView,
                                              newState: Int) {
    
                with(layoutManager as LinearLayoutManager){
    
                    val visibleItemCount = childCount
                    val totalItemCount = itemCount
                    val firstVisibleItem = findFirstVisibleItemPosition()
    
                    if (loading && totalItemCount > previousTotal){
    
                        loading = false
                        previousTotal = totalItemCount
                    }
    
                    if(!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)){
    
                        onScrolledToEnd()
                        loading = true
                    }
                }
            }
        })
    }
    

    And then use it like this:

    youRecyclerView.addOnScrolledToEnd {
        //What you want to do once the end is reached
    }
    

    This solution is based on Kushal Sharma's answer. However, this is a bit better because:

    1. It uses onScrollStateChanged instead of onScroll. This is better because onScroll is called every time there is any sort of movement in the RecyclerView, whereas onScrollStateChanged is only called when the state of the RecyclerView is changed. Using onScrollStateChanged will save you CPU time and, as a consequence, battery.
    2. Since this uses Extension Functions, this can be used in any RecyclerView you have. The client code is just 1 line.

提交回复
热议问题