Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect when a specific item reaches top of a RecyclerView in Android?

I'm creating an app with a list of questions in a RecyclerView. In the same parent layout, I have a static TextView above the RecyclerView that displays instruction for a set of questions. What I want is to change the text in the TextView whenever a specific question reaches the top of the RecyclerView when scrolled. How can I accomplish this?

like image 248
Flavah Avatar asked Apr 26 '16 16:04

Flavah


1 Answers

You would need to listen to the scrolling of your RecyclerView and get the first item displayed onto the screen.

Thanksfully, Android let us set a custom ScrollListener to a RecyclerView and with your LayoutManager you are able to know which item is shown first :

// initialize your RecyclerView and your LayoutManager
mLinearLayoutManager = new LinearLayoutManager(getContext());
mRecyclerView.setLayoutManager(mLinearLayoutManager);

// set a custom ScrollListner to your RecyclerView
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
           // Get the first visible item
           int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition();

           //Now you can use this index to manipulate your TextView

        }
    });

EDIT : added Mateus Gondim clearance about the LayoutManager

like image 141
Gauthier Avatar answered Sep 17 '22 23:09

Gauthier