简体   繁体   English

如何在Recyclerview中加载更多JSON数据

[英]How to load more JSON data in Recyclerview

I have a endless Recyclerview with a onScrollListener implemented that tells me when I reach the bottom of my Recyclerview. 我有一个实现了onScrollListener的无休止的Recyclerview,它告诉我何时到达Recyclerview的底部。 All is set and done. 一切准备就绪。 But the thing is I'm missing the most important part; 但问题是我错过了最重要的部分。 it's how do I load more data in my adapter? 这是如何在适配器中加载更多数据? Do I call another volley request for the next page of my JSON data? 我是否可以为我的JSON数据的下一页调用另一个齐射请求? The API I'm using has a 100 objects limit 我正在使用的API的对象数限制为100

mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            visibleItemCount = mLayoutManager.getChildCount();
            totalItemCount = mLayoutManager.getItemCount();
            pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();

            if (loading){
                if ( (visibleItemCount+pastVisiblesItems) >= totalItemCount ){
                    loading = false;
                    Toast.makeText(getActivity(), "Last Item", Toast.LENGTH_LONG).show();
                }
            }
        }
    });

Thanks! 谢谢!

When you detect that you've reached the end of your current dataset, you should call whatever logic you need to fetch more data. 当检测到已到达当前数据集的末尾时,应调用获取更多数据所需的任何逻辑。 For example, in a paged request you should keep track of whatever pages you've already successfully loaded, and request new data. 例如,在分页请求中,您应该跟踪已经成功加载的所有页面,并请求新数据。

After successfully loading the new data, you should add the models to your data source, then notify the adapter that its dataset has changed, which will update what the user sees on the screen. 成功加载新数据后,应将模型添加到数据源,然后通知适配器其数据集已更改,这将更新用户在屏幕上看到的内容。 You want something similar to the code below: 您需要类似于以下代码的内容:

private int pageNo = 0;

private List<Model> getPagedData(int page) {
    // TODO retrieve JSON from server
    // e.g. GET http://fakewebsite.com?page=2

    if (success) {
        pageNo++;
    }
    else {
        // TODO handle error
    }
}

modelList.addAll(getPagedData(pageNo)); // add newly retrieved data
adapter.notifyDataSetChanged(); // tells RecyclerView to bind new models

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM