RecyclerView滑动距离计算

最近在写关于RecyclerView滑动到最底部时,给出一个判断,是否到达最底部。但不知道为什么,总是得不到ScrollY,一直为0。没办法,只能去网上找一些相关资料。
非常感谢知乎用户-张宇 给的想法。原理很简单,主要就是获取item的高度,和item的总数,然后去计算总的长度。


废话不多说,代码贴上:

    /**
     * 还能向下滑动多少
     */
    private int getDistance(){
        LinearLayoutManager layoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
        View firstVisibItem = mRecyclerView.getChildAt(0);
        int firstItemPosition = layoutManager.findFirstVisibleItemPosition();
        int itemCount = layoutManager.getItemCount();
        int recycleViewHeight = mRecyclerView.getHeight();
        int itemHeight = firstVisibItem.getHeight();
        int firstItemBottom = layoutManager.getDecoratedBottom(firstVisibItem);
        return (itemCount - firstItemPosition - 1)* itemHeight - recycleViewHeight+firstItemBottom;
    }

当前的getDistance()就是剩余的距离。

    /**
     * 已滑动的距离
     */
    private int getDistance(){
        LinearLayoutManager layoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
        View firstVisibItem = mRecyclerView.getChildAt(0);
        int firstItemPosition = layoutManager.findFirstVisibleItemPosition();
        int itemCount = layoutManager.getItemCount();
        int recycleViewHeight = mRecyclerView.getHeight();
        int itemHeight = firstVisibItem.getHeight();
        int firstItemBottom = layoutManager.getDecoratedBottom(firstVisibItem);
        return (firstItemPosition + 1)*itemHeight - firstItemBottom;
    }

计算RecyclerView已经滑动的距离。

    /**
     * 获取RecyclerView滚动距离
     */
    private int getDistance(){
        LinearLayoutManager layoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
        View firstVisibItem = mRecyclerView.getChildAt(0);
        int firstItemPosition = layoutManager.findFirstVisibleItemPosition();
        int itemCount = layoutManager.getItemCount();
        int recycleViewHeight = mRecyclerView.getHeight();
        int itemHeight = firstVisibItem.getHeight();
        int firstItemBottom = layoutManager.getDecoratedBottom(firstVisibItem);
        return (itemCount - firstItemPosition - 1)* itemHeight - recycleViewHeight;
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容