带有滚动加载和下拉刷新的RecyclerView—AutoLoadRecyclerView

本文介绍了一个自定义的RecyclerView组件,该组件支持自动加载更多功能。通过实现特定的滑动监听器,可以在用户接近列表底部时自动触发加载更多数据的动作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码实现

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’ }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值