美文网首页
Android RecyclerView分页监听底部状态源码

Android RecyclerView分页监听底部状态源码

作者: b810b03a141c | 来源:发表于2016-08-04 09:20 被阅读440次

我在这里直接封装成了一个类,直接上代码:

/**
 * Recycler分页
 *
 * @author http://www.lovecoder.cn/
 *         Created by haibo on 2016/7/28.
 */
public class RecyclerPageView extends RecyclerView {
    public RecyclerPageView(Context context) {
        super(context);
    }

    public RecyclerPageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public RecyclerPageView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.addOnScrollListener(new MyOnScrollListener());
    }

    private class MyOnScrollListener extends RecyclerView.OnScrollListener {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            if (newState == SCROLL_STATE_IDLE) {
                LayoutManager layoutManager = getLayoutManager();
                if (getLayoutManager() instanceof StaggeredGridLayoutManager) {
                    StaggeredGridLayoutManager layout = (StaggeredGridLayoutManager) layoutManager;
                    // 获取瀑布流有多少列
                    int column = layout.getColumnCountForAccessibility(null, null);
                    int positions[] = new int[column];
                    // 获取lastItem的positions
                    layout.findLastVisibleItemPositions(positions);
                    for (int i = 0; i < positions.length; i++) {
                        /**
                         * 判断lastItem的底边到recyclerView顶部的距离
                         * 是否小于recyclerView的高度
                         * 如果小于或等于 说明滚动到了底部
                         */
                        if (positions[i] >= (layout.getItemCount() - column)
                                && layout.findViewByPosition(positions[i]).getBottom() <= getHeight()) {
                            Log.d("admin", "到底部了");
                            break;
                        }
                    }
                } else if (getLayoutManager() instanceof LinearLayoutManager) {
                    LinearLayoutManager layout = (LinearLayoutManager) layoutManager;
                    int position = layout.findLastVisibleItemPosition();
                    if (position - 1 == layout.getItemCount()
                            && layout.findViewByPosition(position).getBottom() <= getHeight()) {
                        Log.d("admin", "到底部了");
                    }
                }
            }
            super.onScrollStateChanged(recyclerView, newState);
        }
    }
}

如果感觉帮助到你了,赶快给个赞吧。哈哈
转载请注明出处:http://www.lovecoder.cn/855.html

相关文章

网友评论

      本文标题:Android RecyclerView分页监听底部状态源码

      本文链接:https://www.haomeiwen.com/subject/vtscsttx.html