Added Android code
[wl-app.git] / Android / app / src / main / java / com / moiseum / wolnelektury / components / recycler / EndlessRecyclerOnScrollListener.java
1 package com.moiseum.wolnelektury.components.recycler;
2
3 /**
4  * Created by Piotr Ostrowski on 28.11.2017.
5  */
6
7 import android.support.v7.widget.LinearLayoutManager;
8 import android.support.v7.widget.RecyclerView;
9
10 public abstract class EndlessRecyclerOnScrollListener extends RecyclerView.OnScrollListener {
11
12         public static String TAG = EndlessRecyclerOnScrollListener.class.getSimpleName();
13
14         /**
15          * The total number of items in the dataset after the last load
16          */
17         private int mPreviousTotal = 0;
18         /**
19          * True if we are still waiting for the last set of data to load.
20          */
21         private boolean mLoading = true;
22
23         @Override
24         public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
25                 super.onScrolled(recyclerView, dx, dy);
26
27                 int visibleItemCount = recyclerView.getChildCount();
28                 int totalItemCount = recyclerView.getLayoutManager().getItemCount();
29                 int firstVisibleItem = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
30
31                 if (mLoading) {
32                         if (totalItemCount > mPreviousTotal) {
33                                 mLoading = false;
34                                 mPreviousTotal = totalItemCount;
35                         }
36                 }
37                 int visibleThreshold = 5;
38                 if (!mLoading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
39                         // End has been reached
40                         onLoadMore();
41                         mLoading = true;
42                 }
43         }
44
45         public void reset() {
46                 mPreviousTotal = 0;
47         }
48
49         public abstract void onLoadMore();
50 }