目录

RecyclerView+SwipeRefreshLayout简单几步实现下拉刷新、上拉加载

目录

  • RecyclerView 和SwipeRefreshLayout都是Google官方推出的控件,介绍我这里就不再重复,网上一搜一大把,下面将通过几步简单实现刷新及预加载功能

  • RecyclerView的初始化等这里也不再重复,只粘贴关键步骤

  • 1、布局代码如下

     < android.support.v4.widget.SwipeRefreshLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1">
    
                < android.support.v7.widget.RecyclerView
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="1" />
            < /android.support.v4.widget.SwipeRefreshLayout>
    
  • 2、下拉刷新部分

    mSwipeRefreshLayout.setColorSchemeResources(R.color.blue_FF44BBF0, R.color.green_FF46CD63, R.color.red_FFFC789E, R.color.yellow_FFFFB700);
          mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
              @Override
              public void onRefresh() {
                  LogUtils.d(TAG, "onRefresh start");
                  startRefreshRoomDataTask();
    
              }
          });
    
  • 3、上拉加载部分

     mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
    
                    LogUtils.e(TAG, "onScrollStateChanged: newState :" +newState);
    
                }
    
                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
    
                    LogUtils.e(TAG, "onScrolled: dx" + dx + "---dy" + dy);
    
                    int lastVisibleItem = ((LinearLayoutManager) mLayoutManager).findLastVisibleItemPosition();
                    int totalItemCount = mLayoutManager.getItemCount();//总条目
                    //lastVisibleItem >= totalItemCount - 5 表示剩下5个item实现预加载
                    // dy>0 表示向下滑动,滑动距离
                    if (totalItemCount >= 10 && lastVisibleItem >= totalItemCount - 5 && dy > 0) {
    
                        if (mIsLoadingMore) {
                            ToastUtils.showWithShort(getApplicationContext(), "已经预加载了!");
                        } else {
                            StartLoadMoreTask();//加载更多
                        }
                    }
                }
            });