Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement Endless scrolling using StaggeredLayoutManager

Tags:

I already tried to implement the endless scrolling for LinearLayoutManager and it is successful and tried to copy the LinearLayoutManager implementation to StaggeredGridLayoutManager but it doesn't work.

I just want to get the firstVisibleItem.

in LinearLayoutManager :

int firstVisibleItem = linearLayoutManager.findFirstVisibleItemPosition(int); 

but in StaggeredGridLayoutManager is :

int firstVisibleItem = staggeredGridLayoutManager.findFirstVisibleItemPositions(int[]) 

How to get the firstVisibleItem using (int) not (int[])?

Is there any good approach/implementation about this?

Thanks in advance.

like image 839
Fran Ceriu Avatar asked Mar 16 '15 14:03

Fran Ceriu


1 Answers

I got it working:

You can use one of two methods in the StaggeredGridLayoutManager:

  1. findFirstVisibleItemPositions(int[])
  2. findFirstCompletelyVisibleItemPositions(int[])

Pass an empty int array that will get initialized with the positions and use the one that makes sense for you.

private boolean loading = true; private int pastVisibleItems, visibleItemCount, totalItemCount;  mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener({         @Override         public void onScrolled(RecyclerView recyclerView, int dx, int dy) {          visibleItemCount = mLayoutManager.getChildCount();         totalItemCount = mLayoutManager.getItemCount();         int[] firstVisibleItems = null;         firstVisibleItems = mLayoutManager.findFirstVisibleItemPositions(firstVisibleItems);         if(firstVisibleItems != null && firstVisibleItems.length > 0) {             pastVisibleItems = firstVisibleItems[0];         }          if (loading) {             if ((visibleItemCount + pastVisibleItems) >= totalItemCount) {                 loading = false;                 Log.d("tag", "LOAD NEXT ITEM");             }         }     } }); 
like image 99
Matthew Avatar answered Oct 27 '22 23:10

Matthew