Android code implements Adapterviews and Recyclerview infinite scrolling _android

Source: Internet
Author: User

A common feature of the application is that when users are happy to load more content automatically, this is done by sending a data request when the user slides a certain threshold value.
The same is true: the effect of sliding information needs to be defined in the list of the last visible item, and some type of threshold to facilitate the beginning of the last entry before the arrival of data to start fetching, unlimited scrolling.
The important thing to achieve infinite scrolling is to get the rows of data before the user slides to the bottom, so you need to add a threshold to help you achieve the expectation of getting the data.

Using the ListView and GridView implementations

Each adapterview, such as ListView and GridView, triggers the Onscrolllistener when the user starts a scrolling operation. Using this system, we can define a basic endlessscrolllistener, Support the use of most situations by creating classes that inherit Onscrolllistener.

Package com.codepath.customadapter;

Import Android.widget.AbsListView;
 /** * Created by the Administrator on 2016/7/11. * * Public abstract class Endlessscrolllistener implements Abslistview.onscrolllistener {//Start loading data at least when you are sliding) private in
 T visiblethreshold = 5;
 The current page number that has loaded the data private int currentpage = 0;
 The amount of data in the database after the last load data private int previoustotalitemcount = 0;
 Are we waiting for the last set of data to load private Boolean loading = true;
 Sets the subscript private int startingpageindex = 0 for the start page; Public Endlessscrolllistener () {} public endlessscrolllistener (int visiblethreshold) {this.visiblethreshold = Visib
 Lethreshold; 
  Public Endlessscrolllistener (int visiblethreshold, int startingpageindex) {this.visiblethreshold = VisibleThreshold;
 This.startingpageindex = Startingpageindex; }//This method may be called many times in a slide call, so be cautious when designing//We need some useful parameters to help us when we need to load more data//But first we have to check if we are waiting for the previous load to end//onscroll () When a list or grid view is scrolled, it is called, parameter one: The view parameter of the report state two: the subscript of the first visible item, parameter three: The quantity parameter of the visible item four: The number of items in the ListAdapter @Override public void onscroll (AbSlistview view, int firstvisibleitem, int visibleitemcount, int totalitemcount) {//If the total number of items is 0 and there are no previous entries, then the list is invalid and should be set to the initial shape
   State if (Totalitemcount < previoustotalitemcount) {this.currentpage = This.startingpageindex;
   This.previoustotalitemcount = Totalitemcount;
  if (Totalitemcount = = 0) {this.loading = true;} //If it is still in the load we can check if the data collection has changed, and if it does, it's already done. Loading need to update current//page and data totals if (loading && totalitemcount > Previ
   Oustotalitemcount)) {loading = false;
   Previoustotalitemcount = Totalitemcount;
  currentpage++; //If currently not loaded, we need to check whether the threshold is currently reached, if so we need//load more data, execute Onloadmore if (!loading && (Firstvisibleitem + visibleite
  Mcount + visiblethreshold) >= totalitemcount) {loading = Onloadmore (currentpage + 1, totalitemcount);

 }//define the actual process of loading data, if the data load completion returns False if loading returns true; public abstract boolean onloadmore (int page, int totalitemcount);
@Override public void onscrollstatechanged (Abslistview view, int scrollstate) {//Do not take action}}
 

Note that this is an abstract class, in order to use these, you must inherit this basic class and implement the Onloadmore () method to actually get the data. We define an anonymous class in an activity to inherit Endlessscrolllistener and then connect it to Adapterview.

public class Mainactivity extends activity {
 @Override
 protected void onCreate (Bundle savedinstance) {
  // As usual
   ListView Lvitems = (ListView) Findviewbyid (r.id.lvitens);
   Bind the listener to the top
    Lvitems.setonscrolllistener (new Endlessscrolllistener () {
   @Override public
   Boolean Onloadmore (int page, int totalitemscount) {
    //the code to trigger//load data needed when new data needs to be bound to the list
    add whatever codes are needed to Appen d new items to your Adapterview
    Customloadmoredatafromapi (page); 
    or Customloadmoredatafromapi (totalitemscount); 
    return true; True in data loading, otherwise false; only if more data is actually being loaded; False otherwise.}}
  );
 Load more data public
 void Customloadmoredatafromapi (int offset) {
  //This method typically initiates some network requests and then adds more data to the adapter
  / Attach the offset data as an argument to the request to get a paging
  //parsing API return value and get the new object build adapter
 }


The Onloadmore () method is now automatically triggered when the user slides and triggers a threshold, and the listener gives access to the number of pages and the total amount of data.

Realizing infinite sliding of recyclerview

We can use the same method to define an interface Endlessrecyclerviewscrolllistener and then define a Onloadmore () method to implement it. Because LayoutManager is responsible for the generation and sliding management of the items, we need a layoutmanage instance to gather the necessary information.
Implementing the necessary paging requires such a step:
1). Direct Copy Endlessrecyclerviewscrolllistener.java
2. Call Addonscrolllistener (...) to implement infinite paging in Recyclerview, pass Endlessrecyclerviewscrolllistener instance to realize Onloadmore method to decide when to load the new data
3. In the Onloadmore method, get more item by sending a network request or loading from the source data.

 protected void OnCreate (Bundle savedinstancestate) {//Configure the Recyclerview obtains Recylerview instance Recyclerview
  EMS = (Recyclerview) Findviewbyid (r.id.rvcontacts);
  Linearlayoutmanager Linearlayoutmanager = new Linearlayoutmanager (this);
  Recyclerview.setlayoutmanager (Linearlayoutmanager); ADD the scroll listener rvitems.addonscrolllistener (new Endlessrecyclerviewscrolllistener (Linearlayoutmanager) {@ Override public void Onloadmore (int page, int totalitemscount) {//triggered only when the new data needs to be append Ed to the list//ADD Whatever the code are needed to append new items to the bottom of the list Customloadmoredatafrom 
   API (page);
 }
  }); }//Append more data to the adapter//This method probably sends out a network request and appends new data items T 
 O your adapter. public void Customloadmoredatafromapi (int page) {//Send a API request to retrieve appropriate data using the offset V
  Alue as a parameter. --> DeserializE API response and then construct new objects to append to the adapter//--> Notify the adapter

Endlessrecyclerview

Public abstract class Endlessrecyclerviewscrolllistener extends Recyclerview.onscrolllistener {//the minimum amount of
 Items to have below your current scroll position//before loading.
 private int visiblethreshold = 5;
 The current offset index of data for you have loaded private int currentpage = 0;
 The total number of items in the dataset is the last load private int previoustotalitemcount = 0;
 True If we are still waiting for the last set of data to load.
 Private Boolean loading = true;

 Sets The starting page index private int startingpageindex = 0;

 Recyclerview.layoutmanager Mlayoutmanager;
 Public Endlessrecyclerviewscrolllistener (Linearlayoutmanager layoutmanager) {this.mlayoutmanager = LayoutManager;
  Public Endlessrecyclerviewscrolllistener (Gridlayoutmanager layoutmanager) {this.mlayoutmanager = LayoutManager;
 Visiblethreshold = Visiblethreshold * Layoutmanager.getspancount (); } Public Endlessrecyclerviewscrolllistener (STAGGEREDGRidlayoutmanager layoutmanager) {this.mlayoutmanager = LayoutManager;
 Visiblethreshold = Visiblethreshold * Layoutmanager.getspancount ();
  public int Getlastvisibleitem (int[] lastvisibleitempositions) {int maxSize = 0; 
   for (int i = 0; i < lastvisibleitempositions.length i++) {if (i = = 0) {maxSize = lastvisibleitempositions[i];
   else if (Lastvisibleitempositions[i] > maxSize) {maxSize = lastvisibleitempositions[i];
 } return maxSize;
 }//This happens many times a second during a scroll, so is wary of the code for you. We are given a few useful parameters to help us work out if we need to load some more data,//But-we-check if W
 E are waiting for the previous load to finish.
  @Override public void onscrolled (recyclerview view, int dx, int dy) {int lastvisibleitemposition = 0;

  int totalitemcount = Mlayoutmanager.getitemcount (); if (Mlayoutmanager instanceof Staggeredgridlayoutmanager) {int[] LastvisibleitEmpositions = ((Staggeredgridlayoutmanager) mlayoutmanager). Findlastvisibleitempositions (NULL);
  Get maximum element within the list lastvisibleitemposition = Getlastvisibleitem (lastvisibleitempositions); else if (Mlayoutmanager instanceof linearlayoutmanager) {lastvisibleitemposition = (Linearlayoutmanager) mLayoutMan
  Ager). Findlastvisibleitemposition (); else if (Mlayoutmanager instanceof gridlayoutmanager) {lastvisibleitemposition = (Gridlayoutmanager) mLayoutManager
  ). Findlastvisibleitemposition (); }//If The total item count is zero and the previous isn ' t, assume the//list are invalidated and should be reset BA
   CK to initial state if (Totalitemcount < previoustotalitemcount) {this.currentpage = This.startingpageindex;
   This.previoustotalitemcount = Totalitemcount;
   if (Totalitemcount = = 0) {this.loading = true; }//If it ' s still loading, we check to the if the dataset count has//changed, if so we conclude it has finishEd loading and update the current page//number and total item count.
   if (Loading && (Totalitemcount > Previoustotalitemcount)) {loading = false;
  Previoustotalitemcount = Totalitemcount; //If it isn ' t currently loading, we check to the if we have breached//the visiblethreshold and need to reload MO
  Re data.
  If We do need to reload some more data, we execute onloadmore to fetch the data. Threshold should reflect many total columns there are too if (!loading && (lastvisibleitemposition + Visi
   Blethreshold) > Totalitemcount) {currentpage++;
   Onloadmore (CurrentPage, Totalitemcount);
  Loading = true; }//defines the process for actually loading more data based in page public abstract void Onloadmore (int page, int

Totalitemscount);

 }

Note the problem:
1. For ListView, determine the steps to bind the listener in the OnCreate () method
2. For reliable paging, you need to make sure that the data in the adapter is cleaned before adding new data to the list
For Recyclerview, a more detailed update is recommended when notifying the adapter.
3. For Recyclerview, ensure that the content of the adapter is updated quickly when the data in the list is cleared, so that new onscroll events can be triggered to reset themselves

Show progress bar

In order to show the progress bar at the bottom the ListView is loading. We can set in adapter, we can define two kinds, can be the progress bar type or the text indicates to reach the bottom line, reference: Http://guides.codepath.com/android/ Endless-scrolling-with-adapterviews-and-recyclerview

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.