Detect when RecyclerView reaches the bottom most position while scrolling

后端 未结 11 1882
没有蜡笔的小新
没有蜡笔的小新 2020-11-29 19:56

I have this code for a RecyclerView.

    recyclerView = (RecyclerView)rootview.findViewById(R.id.fabric_recyclerView);
    recyclerView.setLayoutManager(layo         


        
11条回答
  •  难免孤独
    2020-11-29 20:38

    Answer is in Kotlin, it will work in Java. IntelliJ should convert it for you if you copy and paste.

    recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener(){
    
        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
    
            // 3 lines below are not needed.
            Log.d("TAG","Last visible item is: ${gridLayoutManager.findLastVisibleItemPosition()}")
            Log.d("TAG","Item count is: ${gridLayoutManager.itemCount}")
            Log.d("TAG","end? : ${gridLayoutManager.findLastVisibleItemPosition() == gridLayoutManager.itemCount-1}")
    
            if(gridLayoutManager.findLastVisibleItemPosition() == gridLayoutManager.itemCount-1){
                // We have reached the end of the recycler view.
            }
    
            super.onScrolled(recyclerView, dx, dy)
        }
    })
    

    This will also work for LinearLayoutManager because it has the same methods used above. Namely findLastVisibleItemPosition() and getItemCount() (itemCount in Kotlin).

提交回复
热议问题