简体   繁体   中英

Is it possible to detect if a RecyclerView item reached the top of the screen?

I want to detect when a RecyclerView item hits the top end of the screen to make changes to other views. is there a way to do this?

You need to add a scroll listener to your recyclerview object.

recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                    if (!recyclerView.canScrollVertically(-1)) {
                        //top end reached
                    }
            }
        });

Here, -1 means scrolling from bottom to top. Similarly, 1 means scrolling from top to bottom.

Same conventions apply for Horizontal RecyclerView. Just use canScrollHorizontally() instead of canScrollVertically()

if you have your item's position, you can use this

recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
    override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
        super.onScrolled(recyclerView, dx, dy)
        val top = recyclerView.findViewHolderForAdapterPosition(position)?.itemView?.top
        if(top == 0) { 
            //item reached top end 
        }
    }
})

be careful findViewHolderForAdapterPosition will return null when the viewHolder is recycled and no longer visible

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM