recycleView获取距离顶部距离的2种简单方式

2020-10-15  本文已影响0人  初见soulmate

方式一:
此方式在列表显示完成之后无item高度变化的情况下适用,如果有高度动态变化则距离获取会不准确,这种情况下可以用方式二。

int scrollY = 0;//距离顶部距离
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
               
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                scrollY += dy;
            }
        });

方式二:
使用自定义的LinearLayoutManager。

int scrollY = 0;//距离顶部距离
final OffsetLinearLayoutManager offsetLinearLayoutManager = new OffsetLinearLayoutManager(this);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
               
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                scrollY = offsetLinearLayoutManager.computeVerticalOffset();
                           }
        });
recyclerView.setLayoutManager(offsetLinearLayoutManager);
  public static class OffsetLinearLayoutManager extends LinearLayoutManager {
        public OffsetLinearLayoutManager(Context context) {
            super(context);
        }

        private Map<Integer, Integer> heightMap = new HashMap<>();

        public int listHeight = 0;

        @Override
        public void onLayoutCompleted(RecyclerView.State state) {
            super.onLayoutCompleted(state);
            int count = getChildCount();
            listHeight = 0;
            for (int i = 0; i < count; i++) {
                View view = getChildAt(i);
                heightMap.put(i, view.getHeight());
                listHeight += view.getHeight();
            }
        }

        public int computeVerticalOffset() {
            if (getChildCount() == 0) {
                return 0;
            }
            try {
                int firstVisiablePosition = findFirstVisibleItemPosition();
                View firstVisiableView = findViewByPosition(firstVisiablePosition);
                int offsetY = -(int) (firstVisiableView.getY());
                for (int i = 0; i < firstVisiablePosition; i++) {
                    offsetY += heightMap.get(i) == null ? 0 : heightMap.get(i);
                }
                return offsetY;
            } catch (Exception e) {
                return 0;
            }
        }
    }
上一篇下一篇

猜你喜欢

热点阅读