2

I have been looking for a proper API for what I need to do and I am all but certain that there has to be an API. But I am not finding it.

Here is my problem:

I am displaying an ArrayList inside a recycler view. What I need is to know what item in the ArrayList is showing at the top of the recycler view as I scroll up and down. Here is how I set up my recycler view (nothing special):

private ArrayList<Transaction> filteredTransactions = new ArrayList<>();
...            

recyclerView = view.findViewById(R.id.feed_recycle_view);
        recyclerView.setHasFixedSize(true);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager((getActivity()));
        adapter = new FeedAdapter(filteredTransactions);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(adapter);

I came across

recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
}

that provides the listener I need, but I can't figure out how to get the item that appears on top of the view from it.

Thanks in advance

LeaningAndroid
  • 445
  • 2
  • 4
  • 12
  • I think it will help you. https://stackoverflow.com/questions/48687976/how-to-find-the-position-of-current-visible-item-in-recyclerview – mrtcnkryln Jan 28 '20 at 06:00

3 Answers3

1

You can use the following methods of the LinearLayoutManager

int findFirstVisibleItemPosition();
int findFirstCompletelyVisibleItemPosition();
int findLastVisibleItemPosition();
int findLastCompletelyVisibleItemPosition();

Read the official document

skynet
  • 706
  • 4
  • 8
1

findFirstCompletelyVisibleItemPosition() will return the adapter position of the first fully visible view.

You can do it like this:

recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                int itemPoition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstCompletelyVisibleItemPosition();

                // Get the item from the list
                mList.get(itemPoition)

            }
Jaymin
  • 2,879
  • 3
  • 19
  • 35
0

There are some methods which are available in Linear Layout manager like

findFirstCompletelyVisibleItemPosition()

int findFirstVisibleItemPosition()

int findLastCompletelyVisibleItemPosition()

findLastVisibleItemPosition()

Go through the documentation it will surely help you.

Ajeett
  • 814
  • 2
  • 7
  • 18