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);
      }
    }
  }
}

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

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。