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

RecyclerView上拉加载封装代码

程序员文章站 2023-12-05 18:20:28
recyclerview上拉加载,先看效果: 网上有很多这类得框架,不过在自己的项目只用到上拉加载的功能,所以自己封装一个简单点的。 主要依赖baserecypra...

recyclerview上拉加载,先看效果:

RecyclerView上拉加载封装代码

网上有很多这类得框架,不过在自己的项目只用到上拉加载的功能,所以自己封装一个简单点的。

主要依赖baserecypradapter这类

public abstract class baserecypradapter<t> extends recyclerview.adapter<baserecypradapter.baseviewholder> {
  private static final string tag = "baserecypradapter";

  public static final int view_item = 0;
  public static final int view_prog = 1;

  public list<t> mdatalist;

  private final context mcontext;
  private final recyclerview mrecyclerview;
  private int totalitemcount;
  private int lastvisibleitemposition;
  boolean isshowfootview = false;
  private handler handler = new handler();

  private static final int state_normal = 0;
  private static final int state_loading = 1;
  private static final int state_load_complete = 2;
  private int mstate = state_normal;

  public baserecypradapter(context context, recyclerview recyclerview) {
    mcontext = context;
    mrecyclerview = recyclerview;
    if (mrecyclerview.getlayoutmanager() instanceof linearlayoutmanager) {
      final linearlayoutmanager linearlayoutmanager = (linearlayoutmanager) recyclerview.getlayoutmanager();

      mrecyclerview.addonscrolllistener(new recyclerview.onscrolllistener() {
        @override
        public void onscrollstatechanged(recyclerview recyclerview, int newstate) {
          super.onscrollstatechanged(recyclerview, newstate);
          int extent = recyclerview.computeverticalscrollextent();
          int range = recyclerview.computeverticalscrollrange();
          log.e(tag, "\n extent = " + extent + "\n range = " + range);

          if (range > extent) {
            if(!isshowfootview){
              notifydatasetchanged();
            }
            isshowfootview = true;
          } else {
            isshowfootview = false;
          }

          totalitemcount = linearlayoutmanager.getitemcount();
          if (mstate == state_normal && newstate == recyclerview.scroll_state_idle &&
              totalitemcount == lastvisibleitemposition + 1 && range > extent) {
            mstate = state_loading;
            handler.post(new runnable() {
              @override
              public void run() {
                if (mloadmoredatalistener != null) {
                  mloadmoredatalistener.loadmoredata();
                }
              }
            });
          }
        }

        @override
        public void onscrolled(recyclerview recyclerview, int dx, int dy) {
          super.onscrolled(recyclerview, dx, dy);
          lastvisibleitemposition = linearlayoutmanager.findlastvisibleitemposition();
        }
      });
    }

  }


  @override
  public baseviewholder oncreateviewholder(viewgroup parent, int viewtype) {
    baseviewholder holder = null;
    view view = null;
    if (viewtype == view_prog) {
      view = layoutinflater.from(parent.getcontext()).inflate(r.layout.item_footer, parent, false);
    } else {
      view = layoutinflater.from(parent.getcontext()).inflate(getlayoutid(viewtype), parent, false);
    }
    holder = new baseviewholder(view);
    return holder;
  }


  @override
  public void onbindviewholder(baseviewholder holder, int position) {
    if (holder.getitemviewtype() == baserecypradapter.view_prog) {
//      logtool.loge_debug(tag, "onbindviewholder--->" + mstate);
      progressbar progressbar = (progressbar) holder.getview(r.id.progressbar);
      textview text = (textview) holder.getview(r.id.text);

      if (mstate == state_load_complete) {
        progressbar.setvisibility(view.gone);
        text.settext(mcontext.getstring(r.string.没有数据了));
      } else {
        progressbar.setvisibility(view.visible);
        text.settext(mcontext.getstring(r.string.正在加载中));
      }
    }

    if (holder.getitemviewtype() == baserecypradapter.view_item) {
      onbinddata(holder, position);
    }
  }

  @override
  public int getitemcount() {
    if (isshowfootview) {
      return mdatalist == null ? 0 : mdatalist.size() + 1;
    } else {
      return mdatalist == null ? 0 : mdatalist.size();
    }
  }


  //根据不同的数据返回不同的viewtype
  @override
  public int getitemviewtype(int position) {
    if (mdatalist == null)
      return view_item;

    if (position == mdatalist.size()) {
      return view_prog;
    } else {
      return view_item;
    }
  }

  /**
   * 根据type 返回不同的布局
   *
   * @param type
   * @return
   */
  public abstract int getlayoutid(int type);

  public abstract void onbinddata(baseviewholder holder, int position);


  public static class baseviewholder extends recyclerview.viewholder {
    private map<integer, view> mviewmap;
    public view view;

    public baseviewholder(view itemview) {
      super(itemview);

      view = itemview;
      mviewmap = new hashmap<>();
    }

    /**
     * 获取设置的view
     *
     * @param id
     * @return
     */
    public view getview(int id) {
      view view = mviewmap.get(id);
      if (view == null) {
        view = itemview.findviewbyid(id);
        mviewmap.put(id, view);
      }
      return view;
    }
  }

  public void stoploadmore() {
    mstate = state_normal;
    notifydatasetchanged();
  }

  public void loadcomplete() {
    mstate = state_load_complete;
    notifyitemchanged(getitemcount()-1);
  }

  public void setdata(list<t> datas) {
    mdatalist = datas;
  }

  private loadmoredatalistener mloadmoredatalistener;

  public void setloadmoredatalistener(loadmoredatalistener mloadmoredatalistener) {
    this.mloadmoredatalistener = mloadmoredatalistener;
  }

  public interface loadmoredatalistener {
    void loadmoredata();
  }
}

在activity中使用:

public class mainactivity extends appcompatactivity {

  private static final string tag = "recyactivity";
  private recyclerview mrecyclerview;
  private list<string> list = new arraylist<>();
  private myrecyviewadapter madapter;
  private handler handler = new handler();

  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_main);

    init();
  }

  private void init() {
    initview();
    initdata();

    initlistener();
  }

  private void initview() {
    mrecyclerview = (recyclerview) findviewbyid(r.id.recyclerview);

    //创建一个linearlayoutmanager对象
    linearlayoutmanager linearlayoutmanager = new linearlayoutmanager(
        this, linearlayoutmanager.vertical, false);
    mrecyclerview.setlayoutmanager(linearlayoutmanager);

    //创建adapter对象
    madapter = new myrecyviewadapter(this, mrecyclerview);
    mrecyclerview.setadapter(madapter);
    madapter.setdata(list);//设置数据
  }

  //初始化数据
  private void initdata() {
    for (int i = 0; i < 15; i++) {
      list.add("data---------->" + i);
    }
  }


  //初始化监听
  private void initlistener() {
    //加载更多回调监听
    madapter.setloadmoredatalistener(new baserecypradapter.loadmoredatalistener() {
      @override
      public void loadmoredata() {
        //加入null值此时adapter会判断item的type
        log.e(tag, "loadmoredata--->");
        handler.postdelayed(new runnable() {
          @override
          public void run() {
            if (list.size() < 30) {
              for (int i = 0; i < 5; i++) {
                list.add("load more data---------->" + i);
              }
              madapter.stoploadmore();
            } else {
              madapter.loadcomplete();
            }
          }
        }, 500);
      }
    });
  }

  class myrecyviewadapter extends baserecypradapter<string> {

    public myrecyviewadapter(context context, recyclerview recyclerview) {
      super(context, recyclerview);
    }

    @override
    public int getlayoutid(int type) {
      return r.layout.item_view;
    }

    @override
    public void onbinddata(baseviewholder holder, int position) {
      log.e(tag, "onbinddata--->" + position);
      if (mdatalist == null || mdatalist.isempty())
        return;

      textview tv = (textview) holder.getview(r.id.tv_name);
      if (tv != null) {
        tv.settext("data--------->" + position);
      }
    }
  }
}

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