3

I am working on an app which slideshows the images using RecyclerView. I used the below code to horizontally scroll the recycler view.

RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(activity, LinearLayout.HORIZONTAL, false);
imageListRecyclerView.setLayoutManager(mLayoutManager);

Also, I am using the below code to scroll one item at a time.

SnapHelper snapHelper = new PagerSnapHelper();
snapHelper.attachToRecyclerView(imageListRecyclerView);

The problem is that I want to get the position of current visible item using

holder.getAdapterPosition()

but it is not working. Can anyone tell how to do it?

Tavinder Singh
  • 380
  • 1
  • 7
  • 17

2 Answers2

6

There are some helper methods of LinearLayoutManager

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

int findFirstVisibleItemPosition()
Returns the adapter position of the first visible view.

int findLastCompletelyVisibleItemPosition()
Returns the adapter position of the last fully visible view.

findLastVisibleItemPosition()

for more information check this official document.

ziLk
  • 3,120
  • 21
  • 45
  • 1
    I am using these in onScrollListener() of Recyclerview, and it doesn't works. – Tavinder Singh Feb 08 '18 at 15:03
  • What problem are you facing while using these? @TavinderSingh – karandeep singh Feb 08 '18 at 18:01
  • @karandeepsingh I'm using the same in onScrollListener and the reason it doesn't work is because as the user scrolls to let's say previous days, I prepend data to my datasource, and notifyItemInserted runs. Once it runs, `findFirstVisibleItemPosition` returns 0 – SudoPlz Jun 01 '18 at 13:35
2

Following Linear / Grid LayoutManager methods can be used to check which items are visible

LinearLayoutManager layoutManager = ((LinearLayoutManager) mRecyclerView.getLayoutManager());

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

and if you want to track is item visible on screen for some threshold means user spent enough time to view the content then you can refer to the following blog.

a very nice blog which demonstrates the use of scroll callbacks of LayoutManager and RxJava Subscribers to track item visibility meets the threshold https://proandroiddev.com/detecting-list-items-perceived-by-user-8f164dfb1d05

Sumit Jain
  • 1,100
  • 1
  • 14
  • 27