欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android代码实现AdapterViews和RecyclerView无限滚动

程序员文章站 2024-03-05 14:53:08
应用的一个共同的特点就是当用户欢动时自动加载更多的内容,这是通过用户滑动触发一定的阈值时发送数据请求实现的。 相同的是:信息实现滑动的效果需要定义在列表中最后一个可见项...

应用的一个共同的特点就是当用户欢动时自动加载更多的内容,这是通过用户滑动触发一定的阈值时发送数据请求实现的。
相同的是:信息实现滑动的效果需要定义在列表中最后一个可见项,和某些类型的阈值以便于开始在最后一项到达之前开始抓取数据,实现无限的滚动。
实现无限滚动的现象的重要之处就在于在用户滑动到最低端之前就行数据的获取,所以需要加上一个阈值来帮助实现获取数据的预期。

使用listview和gridview实现

每个adapterview 例如listview 和gridview 当用户开始进行滚动操作时候都会触发onscrolllistener .使用这个系统我们就可以定义一个基本的endlessscrolllistener ,通过创造继承onscrolllistener 的类来支持大多数情况下的使用。

package com.codepath.customadapter;

import android.widget.abslistview;

/**
 * created by administrator on 2016/7/11.
 */
public abstract class endlessscrolllistener implements abslistview.onscrolllistener {
 //在你滑动项下最少为多少时开始加载数据
 private int visiblethreshold = 5;
 //已经加载数据的当前页码
 private int currentpage = 0;
 //上一次加载数据后数据库的数据量
 private int previoustotalitemcount = 0;
 //我们是否在等待最后一组数据的加载
 private boolean loading = true;
 //设置开始页的下标
 private int startingpageindex = 0;
 public endlessscrolllistener() {

 }
 public endlessscrolllistener(int visiblethreshold) {
  this.visiblethreshold = visiblethreshold;
 }
 public endlessscrolllistener(int visiblethreshold, int startingpageindex) {
  this.visiblethreshold = visiblethreshold;
  this.startingpageindex = startingpageindex;
 }
 //这个方法可能会在滑动调用很多次,所以在设计时要保持谨慎
 //我们需要一些有用的参数来帮助我们,当我们需要加载更多数据的时候
 //但是我们首先要检查是否我们在等待先前的加载结束

//onscroll()当列表或网格视图被滚动后将会调用,参数一:报告状态的视图参数二:第一个可以看见的项的下标,参数三:可见项的数量参数四:listadapter中所有的项数
 @override
 public void onscroll(abslistview view, int firstvisibleitem, int visibleitemcount, int totalitemcount) {

  //如果总项数为0,而且先前没有项,那么这个列表是无效的应该被设定为初始状态
  if (totalitemcount < previoustotalitemcount) {
   this.currentpage = this.startingpageindex;
   this.previoustotalitemcount = totalitemcount;
   if (totalitemcount == 0) {this.loading = true;}
  }
  //如果仍在加载中我们可以检查一下数据集合是否改变了,如果改变的话那就是已经完成了loading需要更新当前
  //页数和数据总量
  if (loading && (totalitemcount > previoustotalitemcount)) {
   loading = false;
   previoustotalitemcount = totalitemcount;
   currentpage++;
  }
  //如果当前没有加载,我们需要检查当前是否达到了阈值,如果是的话我们需要
  //加载更多的数据,执行onloadmore
  if (!loading && (firstvisibleitem + visibleitemcount + visiblethreshold) >= totalitemcount) {
   loading = onloadmore(currentpage + 1, totalitemcount);
  }
 }
 //定义实际加载数据的过程,如果数据加载完成返回false,如果正在加载返回true;
 public abstract boolean onloadmore(int page, int totalitemcount);

 @override
 public void onscrollstatechanged(abslistview view, int scrollstate) {
  //不采取动作
 }
}

要注意的是这是一个抽象的类,为了要使用这些,必须继承这个基本的类并且实现onloadmore()方法实际的获取数据, 我们在一个活动中定义一个匿名的类来继承endlessscrolllistener然后将其连接adapterview上

public class mainactivity extends activity {
 @override
 protected void oncreate(bundle savedinstance) {
  //向平常一样
   listview lvitems = (listview) findviewbyid(r.id.lvitens);
   //将监听器绑定到上面
    lvitems.setonscrolllistener(new endlessscrolllistener() {
   @override
   public boolean onloadmore(int page, int totalitemscount) {
    // 当新数据需要绑定到列表上的时候触发
    // 加载数据需要的代码add whatever code is needed to append new items to your adapterview
    customloadmoredatafromapi(page); 
    // or customloadmoredatafromapi(totalitemscount); 
    return true; //数据加载中为true,不然为false; only if more data is actually being loaded; false otherwise.
   }
  });
 }
 //加载更多的数据
 public void customloadmoredatafromapi(int offset) {
  //这个方法通常会发起一些网络请求,然后向适配器添加更多的数据
  //将偏移量数据作为参数附在请求里来获得一个数据的分页
  //解析api返回的值并且获得新的对象构建适配器
 }
}

现在当用户滑动并且触发阈值时会自动触发onloadmore() 方法,而且监听器给予了对于页数和数据总量的访问权限。

实现recyclerview的无限滑动

我们可以使用相同的方法来定义一个接口endlessrecyclerviewscrolllistener 然后定义一个onloadmore() 的方法来进行实现。由于layoutmanager负责项的生成和滑动的管理,我们需要一个layoutmanage的实例来收集必要的信息。
实现必要的分页需要这样的步骤:
1).直接复制endlessrecyclerviewscrolllistener.java
2).调用addonscrolllistener(...) 在recyclerview 中来实现无限的分页,传递endlessrecyclerviewscrolllistener的实例来实现onloadmore 方法来决定什么时候来加载新的数据
3).在onloadmore 方法中通过发送网络请求或者从源数据加载来获得更多item。

 protected void oncreate(bundle savedinstancestate) {
  // configure the recyclerview获得recylerview的实例
  recyclerview rvitems = (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 new data needs to be appended to the list
    // add whatever code is needed to append new items to the bottom of the list
    customloadmoredatafromapi(page); 
   }
  });
 }

 // append more data into the adapter
 // this method probably sends out a network request and appends new data items to your adapter. 
 public void customloadmoredatafromapi(int page) {
  // send an api request to retrieve appropriate data using the offset value as a parameter.
  // --> deserialize api response and then construct new objects to append to the adapter
  // --> notify the adapter of the changes
 }
}

endlessrecyclerview

public abstract class endlessrecyclerviewscrolllistener extends recyclerview.onscrolllistener {
 // the minimum amount of items to have below your current scroll position
 // before loading more.
 private int visiblethreshold = 5;
 // the current offset index of data you have loaded
 private int currentpage = 0;
 // the total number of items in the dataset after 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 be wary of the code you place here.
 // we are given a few useful parameters to help us work out if we need to load some more data,
 // but first we check if we 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) mlayoutmanager).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 is invalidated and should be reset back 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 see 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 see if we have breached
  // the visiblethreshold and need to reload more data.
  // if we do need to reload some more data, we execute onloadmore to fetch the data.
  // threshold should reflect how many total columns there are too
  if (!loading && (lastvisibleitemposition + visiblethreshold) > totalitemcount) {
   currentpage++;
   onloadmore(currentpage, totalitemcount);
   loading = true;
  }
 }

 // defines the process for actually loading more data based on page
 public abstract void onloadmore(int page, int totalitemscount);

}

注意问题:
 1.对于listview,确定将绑定监听器的步骤放在oncreate()的方法中
 2.为可加可靠的进行分页,需要确定在向列表中添加新数据的时候先清理适配器中的数据
对于recyclerview来说在通知适配器时推荐更细致的更新。
 3.对于recyclerview来说确保在清除列表中的数据的时候迅速的通知适配器内容更新了,以便于可以触发新的onscroll事件,重置自己 

展示进度条

为了在底部展示进度条证明listview正在加载。我们可以在adapter中进行设置,我们可以定义两类,可以是进度条类型或者是文本表明达到了最底行,参考:http://guides.codepath.com/android/endless-scrolling-with-adapterviews-and-recyclerview

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。