如何确定RecyclerView的最后一项在屏幕上可见? [英] How can I identify that RecyclerView's last item is visible on screen?

查看:1246
本文介绍了如何确定RecyclerView的最后一项在屏幕上可见?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个RecyclerView,并将数据列表添加到RecyclerView中.当最后一个RecyclerView项目在屏幕上可见时,我想在列表中添加更多数据.之后,我要进行Web服务调用并更新RecyclerView数据.我该如何实现?

I have one RecyclerView and I added list of data into the RecyclerView. I wanted to add more data in list, when last RecyclerView item is visible on screen. After that I want to make a web service call and update the RecyclerView data. How can I achieve this?

有什么建议吗?

推荐答案

一个选项涉及编辑LayoutManager.这里的想法是找到最后一个可见项目的位置.如果该位置等于数据集的最后一项,则应触发重新加载.

One option would involve editing your LayoutManager. The idea here is to find the position of the last visible item. If that position is equal to the last item of your dataset, then you should trigger a reload.

    @Override
    public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {

        final int result = super.scrollVerticallyBy(dy, recycler, state);

        if (findLastVisibleItemPosition() == mData.length - 1) {
           loadMoreData();
        } 

        return result;

    }

    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        super.onLayoutChildren(recycler, state);

        if (findLastVisibleItemPosition() == mData.length - 1) {
           loadMoreData();
        } 
    }

或者,您也可以通过适配器的onBindViewHolder方法执行此操作,尽管这确实有点"hack":

Alternatively, you could do this via your adapter's onBindViewHolder method, although this is admittedly a bit of a "hack":

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (position == mData.length - 1) {
            // load more data here.
        }

        /// binding logic
    }

第三个选项是将OnScrollListener添加到RecyclerView. @velval在此页面上的答案很好地说明了这一点.

3rd option would be to add an OnScrollListener to the RecyclerView. @velval's answer on this page explains this well.

无论您选择哪个选项,都应包含代码以防止数据加载逻辑触发太多次(例如,在之前的获取更多数据的请求完成并返回新数据之前).

Regardless which option you go for, you should also include code to prevent the data load logic from triggering too many times (e.g., before the previous request to fetch more data completes and returns new data).

这篇关于如何确定RecyclerView的最后一项在屏幕上可见?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆