Android - Detect when the last item in a RecyclerView is visible

后端 未结 4 761
挽巷
挽巷 2020-12-03 04:46

I have a method that will check if the last element in a RecyclerView is completely visible by the user, so far I have this code The problem is how to check if the Recycler

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-03 05:49

    You can create a callback in your adapter which will send a message to your activity/fragment every time when the last item is visible.

    For example, you can implement this idea in onBindViewHolder method

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
        if(position==(getItemCount()-1)){
            // here goes some code
            //  callback.sendMessage(Message);
         }
        //do the rest of your stuff 
    }
    

    UPDATE

    Well, I know it's been a while but today I ran into the same problem, and I came up with a solution that works perfectly. So, I'll just leave it here if anybody ever needs it:

    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            LinearLayoutManager layoutManager=LinearLayoutManager.class.cast(recyclerView.getLayoutManager());
            int totalItemCount = layoutManager.getItemCount();
            int lastVisible = layoutManager.findLastVisibleItemPosition();
    
            boolean endHasBeenReached = lastVisible + 5 >= totalItemCount;
            if (totalItemCount > 0 && endHasBeenReached) {
                //you have reached to the bottom of your recycler view
            }
        }
    });
    

提交回复
热议问题