0

I have a RecyclerView with LinearLayout manager, and I need to interact with last item of RecyclerView in his onScrolled method.

I`m using such code:

lm = new LinearLayoutManager(getActivity());
...
// rv initializing
...
rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            Log.d("Last item", ""+lm.findLastCompletelyVisibleItemPosition());
        }
    });

and when I scroll list abruptly, i have such output in Logcat:

D/Last item: 11
D/Last item: 11
D/Last item: 13
D/Last item: 15
D/Last item: 19
D/Last item: 21
D/Last item: 23
D/Last item: 24
D/Last item: 26
D/Last item: 28
D/Last item: 30
D/Last item: 32
D/Last item: 33
D/Last item: 35

As you can see, some elements just skipped by layout manager. So, my question is: how I can avoid this and get position of all elements?

1 Answers1

0

I had some questions and was able to find a way that might help you: I use horizontal recyclerView and an item that takes up screen 3/4, I calculated item width to get current item position, like this:

recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
       super.onScrolled(recyclerView, dx, dy);
       int horizontalScrollRange = recyclerView.computeHorizontalScrollRange();
       int scrollOffset = recyclerView.computeHorizontalScrollOffset();
       int currentItem = 0;
       float itemWidth = horizontalScrollRange * 1.0f / deviceGoodsItems.size();
       itemWidth = (itemWidth == 0) ? 1.0f : itemWidth;
       if (scrollOffset != 0) {
              currentItem = Math.round(scrollOffset / itemWidth);
       }
       currentItem = (currentItem < 0) ? 0 : currentItem;
       currentItem = (currentItem >= deviceGoodsItems.size()) ? deviceGoodsItems.size() - 1 : currentItem;

       }
});
Unheilig
  • 16,196
  • 193
  • 68
  • 98
Fan sion
  • 1
  • 1