帶有滾動加載和下拉刷新的RecyclerView—AutoLoadRecyclerView

代碼實現

public class AutoLoadRecyclerView extends RecyclerView {
        private loadMoreListener loadMoreListener;
        private AutoLoadScroller autoLoadScroller;
        private boolean isLoading = false;
        public interface loadMoreListener {
            void onLoadMore();
        }   //實現兩個構造函數
    public AutoLoadRecyclerView(Context context) {
        this(context,null);
    }
      //在佈局文件中調用的方法
    public AutoLoadRecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        autoLoadScroller = new AutoLoadScroller();
        addOnScrollListener(autoLoadScroller);
    }


public void setLoadMoreListener(AutoLoadRecyclerView.loadMoreListener loadMoreListener) {
            this.loadMoreListener = loadMoreListener;
        }

 public boolean isLoading() {
            return isLoading;
        }

 public void setLoading(boolean loading) {
            isLoading = loading;
        }

 public void removeAutoScroller() {
            removeOnScrollListener(autoLoadScroller);
        }

//創建自定義滑動監聽,繼承OnScrollListener

 private class AutoLoadScroller extends  OnScrollListener{
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);

 //判斷是否是列表排列

 if(getLayoutManager() instanceof LinearLayoutManager){

  //findLastVisibleItemPosition獲取列表底部item對應記錄下標

  int lastVisiblePos = ((LinearLayoutManager)getLayoutManager()).findLastVisibleItemPosition();
                //獲取適配器當前頁面的條目個數
                int itemCount = getAdapter().getItemCount();
                if (loadMoreListener != null && !isLoading && lastVisiblePos > itemCount - 2 && dy > 0) {
                    loadMoreListener.onLoadMore();
                    isLoading = true;
                }
            }
        }
    }
  }

實現xml佈局

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp">
    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/refresh_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <itheima.com.goolgemarket.view.AutoLoadRecyclerView
            android:id="@+id/rv"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </android.support.v4.widget.SwipeRefreshLayout>
</FrameLayout>

實現展示數據

public class HomeFragment extends Fragment {
    @BindView(R.id.rv)
    AutoLoadRecyclerView rv;
    @BindView(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;      ————>  插件拓展:④插件:ButterKnife(黃油刀)——> 一鍵處理 findViewById控件插件
    private int currPageIndex = 0;
    private AppAdapter adapter;
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //1.佈局xml使用code
        int layout = R.layout.fragment_home;
        //2.閱讀接口文檔
        //3.可在調試模式獲取json
        currPageIndex = 0;
        HttpUtils.get(ApiUrls.HOME + "?index=" + currPageIndex, callback);
        //支持下拉刷洗與滾動加載
        View view = inflater.inflate(layout, container, false);
        ButterKnife.bind(this, view);
        //編寫下拉刷新事件的處理
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //1:清空數據  2:添加新獲取首頁數據  3:列表刷新
                Toast.makeText(getContext(), "下拉刷新中", Toast.LENGTH_SHORT).show();
                currPageIndex = 0;
                HttpUtils.get(ApiUrls.HOME + "?index=" + currPageIndex, callback);
            }
        });
        //設置滑動加載數據事件
        rv.setLoadMoreListener(new AutoLoadRecyclerView.loadMoreListener() {
            @Override
            public void onLoadMore() {
                if (currPageIndex == 2) {
                    Toast.makeText(getContext(), "已經沒有數據了...", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getContext(), "加載更多中", Toast.LENGTH_SHORT).show();
                    currPageIndex += 1;
                    HttpUtils.get(ApiUrls.HOME + "?index=" + currPageIndex, callback);
                }
            }
        });
        return view;
    }
    //實現回調
    DefaultCallBack callback = new DefaultCallBack() {
        @Override
        public void onStart(int what) {
            super.onStart(what);
            if (currPageIndex == 0) {
                refreshLayout.setRefreshing(true);
            }
        }
        @Override
        public void onFinish(int what) {
            super.onFinish(what);
            if (currPageIndex == 0) {
                refreshLayout.setRefreshing(false);
            }
        }
        protected void createView(String json) {
            HomeWebInfo info = new Gson().fromJson(json, HomeWebInfo.class);
            if (currPageIndex == 0) {//首頁邏輯
                if (adapter == null) {
                    //5.高級控件的顯示
                    rv.setLayoutManager(new LinearLayoutManager(getContext()));
                    //創建控件,設置適配器
                    adapter = new AppAdapter(info.list);
                    rv.setAdapter(adapter);
                } else {
                    adapter.getData().clear();//清空之前數據
                    adapter.getData().addAll(info.list);//添加新獲取的首頁數據
                    adapter.notifyDataSetChanged();
                    Toast.makeText(getContext(), "下拉刷新成功", Toast.LENGTH_SHORT).show();
                }
            } else {
                //添加下一頁數據
                adapter.getData().addAll(info.list);
                adapter.notifyDataSetChanged();
                Toast.makeText(getContext(), "加載更多完成", Toast.LENGTH_SHORT).show();
                //加載完成,設置loading爲false可以加載下一頁
                rv.setLoading(false);
            }
        }
    };
}

插件:ButterKnife(奶油刀)——> 一鍵處理 findViewById控件插件

1.安裝插件 setting -> plugins
2.網絡下載butterknife支持包 project structure -> dependencies
3.在project的build.gradle中依賴包
dependencies { classpath ‘com.android.tools.build:gradle:2.2.2’
classpath ‘com.neenbedankt.gradle.plugins:android-apt:1.8’ }
4.在app的build.gradle中首行增加 apply plugin: ‘android-apt’
dependencies { compile ‘com.jakewharton:butterknife:8.4.0’
apt ‘com.jakewharton:butterknife-compiler:8.4.0’ }

發佈了68 篇原創文章 · 獲贊 30 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章