- polbins / EndlessListActivity.java
- 3 Android RecyclerView Load More On Scroll Examples
- How To Implement Pagination In Android RecyclerView
- How To Add OnScrollListener With RecyclerView
- Simple Android RecyclerView Load More On Scroll Example
- MainActivity.kt
- RecyclerViewAdapter.kt
- Grid RecyclerView Pagination Example — Different Approach
- RecyclerViewAdapter.kt
- Retrofit Android RecyclerView Infinite Scroll Example
- Обнаружение начала и конца прокрутки в recyclerview
- 7 ответов
polbins / EndlessListActivity.java
Endless Scroll Listener for Recycler Views
Endless Scrolling for Paginated APIs as shown in : Google Design — Progress Activity Behavior which has the following components:
- Endless Scroll Listener for Recycler Views
- concrete class implements loadMore(pageNumber) to signal the API to load more data
- List Adapter which shows:
- Empty View when given an empty Item List (TextView)
- Progress View when we are currently loading (ProgressBar)
- addAll(. ) to append data to the end of the list
- setIsAppending(boolean) for signaling the start/end of data loading
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
public class EndlessListActivity extends Activity < |
private EndlessRecyclerOnScrollListener mEndlessScrollListener; |
private EndlessListAdapter mAdapter; |
@Override |
protected void onCreate ( Bundle savedInstanceState ) < |
super . onCreate(savedInstanceState); |
RecyclerView listView = ( RecyclerView ) findViewById( R . id . list); |
LinearLayoutManager linearLayoutManager = new LinearLayoutManager ( this ); |
mEndlessScrollListener = new EndlessRecyclerOnScrollListener (mLinearLayoutManager) < |
@Override |
public void onLoadMore ( int current_page ) < |
// try to get adapter from the recycler view, and cast it appropriately |
EndlessListAdapter adapter = ( EndlessListAdapter ) mListView . getAdapter(); |
if (adapter != null ) < |
// signal adapter that loading attempt has started |
adapter . setIsAppending( true ); |
adapter . notifyItemInserted(adapter . getItemCount()); |
// Call your API Here |
loadMore(current_page); |
> |
> |
>; |
listView . setLayoutManager(linearLayoutManager); |
listview . addOnScrollListener(mEndlessScrollListener); |
// Do your RecyclerView stuff here |
mAdapter = new EndlessListAdapter ( . ); |
> |
// When your Data from the API is loaded, |
// set the Total Entries on your Endless Scroll Listener |
public void onDataLoaded ( int serverTotalEntries ) < |
mEndlessScrollListener . setTotalEntries(serverTotalEntries); |
> |
// After finishing loading of new data, |
// add it to your adapter |
public void onLoadMore ( List D > dataList ) < |
mAdapter . addAll(dataList); |
mAdapter . setIsAppending( false ); |
> |
> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
public abstract class EndlessListAdapter extends RecyclerView . ViewHolder > |
extends RecyclerView . Adapter VH > < |
private boolean mIsAppending = false ; |
protected static final int VIEW_TYPE_PROGRESS = 333 ; |
public EndlessListAdapter ( List D > dataList ) < |
super (dataList); |
> |
public boolean isAppending () < |
return mIsAppending; |
> |
public void setIsAppending ( boolean isAppending ) < |
mIsAppending = isAppending; |
> |
@Override |
public int getItemCount () < |
return isAppending() ? |
super . getItemCount() + 1 : super . getItemCount(); |
> |
@Override |
public int getItemViewType ( int position ) < |
return (isAppending() && position >= super . getItemCount()) ? |
VIEW_TYPE_PROGRESS : super . getItemViewType(position); |
> |
@Override |
public final VH onCreateViewHolder ( ViewGroup parent , int viewType ) < |
RecyclerView . ViewHolder vh; |
if (viewType == VIEW_TYPE_PROGRESS ) < |
View v = LayoutInflater . from(parent . getContext()) |
.inflate( R . layout . layout_progress_bar, parent, false ); |
vh = new ProgressViewHolder (v); |
> else < |
vh = super . onCreateViewHolder(parent, viewType); |
> |
return ( VH ) vh; |
> |
@Override |
public final void onBindViewHolder ( VH holder , int position ) < |
if (holder instanceof ProgressViewHolder ) < |
// do nothing |
> else < |
super . onBindViewHolder(holder, position); |
> |
> |
public static class ProgressViewHolder extends RecyclerView . ViewHolder < |
public ProgressViewHolder ( View v ) < |
super (v); |
> |
> |
> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
public abstract class EndlessRecyclerOnScrollListener extends RecyclerView . OnScrollListener < |
private boolean mLoading = false ; // True if we are still waiting for the last set of data to load |
private int previousItemCount = 0 ; // The total number of items in the dataset after the last load |
private int mTotalEntries; // The total number of entries in the server |
private int current_page = 1 ; // Always start at Page 1 |
private LinearLayoutManager mLinearLayoutManager; |
public EndlessRecyclerOnScrollListener ( LinearLayoutManager linearLayoutManager ) < |
mLinearLayoutManager = linearLayoutManager; |
> |
// Concrete classes should implement the Loading of more data entries |
public abstract void onLoadMore ( int current_page ); |
public void setTotalEntries ( int totalEntries ) < |
mTotalEntries = totalEntries; |
> |
// when you’re RecyclerView supports refreshing, also refresh the count |
public void refresh () < |
current_page = 1 ; |
previousItemCount = 0 ; |
> |
@Override |
public void onScrolled ( RecyclerView recyclerView , int dx , int dy ) < |
super . onScrolled(recyclerView, dx, dy); |
int visibleItemCount = recyclerView . getChildCount(); |
int totalItemCount = mLinearLayoutManager . getItemCount(); |
int firstVisibleItem = mLinearLayoutManager . findFirstVisibleItemPosition(); |
if (mLoading) < |
int diffCurrentFromPrevious = totalItemCount — previousItemCount; |
// check if current total is greater than previous (diff should be greater than 1, for considering placeholder) |
// and if current total is equal to the total in server |
if ((diffCurrentFromPrevious > 1 ) || |
totalItemCount >= mTotalEntries) < |
mLoading = false ; |
previousItemCount = totalItemCount; |
> |
> else < |
if (totalItemCount >= mTotalEntries) < |
// do nothing, we’ve reached the end of the list |
> else < |
// check if the we’ve reached the end of the list, |
// and if the total items is less than the total items in the server |
if ((firstVisibleItem + visibleItemCount) >= totalItemCount && |
totalItemCount mTotalEntries) < |
onLoadMore( ++ current_page); |
mLoading = true ; |
previousItemCount = totalItemCount; |
> |
> |
> |
> |
> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Источник
3 Android RecyclerView Load More On Scroll Examples
This post contains affiliate links. If you use these links to buy something I may earn a commission. Thanks.”
We are using lots of apps that load data while we scrolling. Facebook, Instagram, and more apps using this technique. This technique helps users to wait less time.
So if you are planning to make an app like that, using RecyclerView. Then this post is for you.
In this post, You will learn how to use Load More on Scroll or pagination or endless scrolling or infinite scroll or whatever you call, with RecyclerView.
Before that, I recommend reading our RecyclerView Tutorial Guide.
This post is not dealing with the pagination library.
How To Implement Pagination In Android RecyclerView
In this post, I am going to talk about two methods, that implement pagination in RecyclerView. But in both methods, we will use scroll Listener with RecyclerView to listen to scroll events. When RecyclerView scrolls, onScrolled() method gets called.
So first learn how to add OnScrollListener with Recyclerview.
How To Add OnScrollListener With RecyclerView
Simple Android RecyclerView Load More On Scroll Example
Let’s make a linear list Using RecyclerView and add an endless scroll feature.
After the implementation of scroll listener, we should do the following
- we use findLastCompletelyVisibleItemPosition() to get the position of last visible item.
- Use a variable which checks progressbar loading or not
- If last item reached and progressbar not loading, loadmore() gets called. Using Handler, we add “load” in list.
- When adapter checks list, ProgressBar gets added.
- Next data chunks received, ProgressBar gets removed and data got added.
- For showing different View types. here
- Data row
- ProgressBar
Make use of getViewType() method in RecyclerView.Adapter.
MainActivity.kt
- It’s better to use Handler.post() or RecyclerView.post() while updating adapter when RecyclerView measures.
- findLastCompletelyVisibleItemPosition() returns only completely visible Item’s position, So make sure your last view is fully visible.
- 2500 milliseconds — delay time
RecyclerViewAdapter.kt
- getItemViewType(int position) method returns VIEW_TYPE_PROGRESS, if data is «load». Otherwise, it returns VIEW_TYPE_DATA.
- Based on ViewType, In onCreateViewHolder layout will get inflated.
Grid RecyclerView Pagination Example — Different Approach
Now we will make a Grid RecyclerView with pagination. Sometimes we need to load data before the last item loads.
For that purpose, you can make use of this approach.
Okay, what we do in this approach.
we define 3 variables, visibleThreshold, lastVisibleItem, and totalItemCount.
- visibleThreshold : limit of items that user want to see before loading next items
- lastVisibleItem : just like name, last visible item position in adapter
- totalItemCount : No.of items in adapter
- Make ProgressBar width to maximum using setSpanSizeLookup() method
RecyclerViewAdapter.kt
Retrofit Android RecyclerView Infinite Scroll Example

In this example, we will load data from the internet using Retrofit2. You can download PHP(data.php) code from the Source Code link shown at the top.
I am using Android Studio 3.5.
Let’s create a project.
In choosing your project window, click on «Empty Activity» and click Next.
Name: RetrofitRecyclerViewLoadMoreEx
I am going to use AndroidX library, so make sure you tick on the androidx.* artifacts.
That’s your choice, but I recommend to use this one.
Click «Finish«.
add below dependencies
- Gson converter : It helps to serialize and deserialize JSON data.
Источник
Обнаружение начала и конца прокрутки в recyclerview
Мне нужно определить начало / конец и направление прокрутки в recyclerview. У прослушивателя прокрутки есть два метода: onScrolled() и onScrollStateChanged() . Первый метод вызывается после запуска прокрутки (действительно, вызывается onScrolled (), а не onScrolling ()). Второй метод дает информацию о состоянии, но у меня нет информации о направлении. Как я могу достичь своей цели?
7 ответов
Шаг 1 Вы можете создать класс, расширяющий RecyclerView.OnScrollListener, и переопределить эти методы
Шаг 2- Поскольку setOnScrollListener устарел, лучше использовать addOnScrollListener
Вот полное решение для выполнения действия после остановки прокрутки (для RecyclerView)
Который исправил мое исключение OutOfBounds, связанное с прокруткой recyclerView
Думаю, другие ответы не касаются вашей болевой точки.
О вопросе
Как вы сказали, RecycleView вызовет onScrollStateChanged () перед методом onScrolled (). Однако метод onScrollStateChanged () может сообщить вам только три состояния RecycleView:
- SCROLL_STATE_IDLE
- SCROLL_STATE_DRAGGING
- SCROLL_STATE_SETTLING
Это означает, что предположим, что RecycleView сейчас находится наверху, если пользователь прокручивает страницу вверх, он может запускать только метод onScrollStateChanged() , но не метод onScrolled() . И если пользователь прокручивает страницу вниз, сначала запускается метод onScrollStateChanged() , а затем метод onScrolled() .
Затем возникает проблема: SCROLL_STATE_DRAGGING может только сказать вам, что пользователь перетаскивает представление, но не может сказать направление его перетаскивания.
Вы должны объединить с методом dy from onScrolled() для определения направления перетаскивания, но onScrolled() не запускается с onScrollStateChanged() .
MySolution:
Запишите состояние прокрутки при срабатывании onScrollStateChanged() , затем задержите время, например 10 мс, проверьте, есть ли движение по оси Y, и сделайте вывод о направлении перетаскивания.
Источник