Android: How to get the current X offset of RecyclerView?

longi picture longi · Dec 16, 2014 · Viewed 87.5k times · Source

I'm using a Scrollview for an infinite "Time Picker Carousel" and found out, that it is not the best approach (last question)

Now, I found the Recycler View but I am unable to get the current scroll offset in X direction of the recyclerView? (Let's say each item is 100px width, and the second item is only visible to 50%, so the scroll-offset is 150px)

  • all items have the same width, but therer is some gap before the first, after the last item
  • recyclerView.getScrollX() returns 0 (docs say: initial scroll value)
  • the LayoutManager has findFirstVisibleItemPosition, but I cannot calculate the X offset with that

UPDATE

I just found a way to keep tracking the X-Position, while updating the value with the onScrolled callback, but I would prefer getting the actual value instead of tracking it all the time!

private int overallXScroll = 0;
//...
mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);

            overallXScroll = overallXScroll + dx;

            Log.i("check","overallXScroll->" + overallXScroll);

        }
    });

Answer

Umar Qureshi picture Umar Qureshi · Sep 30, 2015

RecyclerView already have method to get horizontal and vertical scroll offset

mRecyclerView.computeHorizontalScrollOffset()
mRecyclerView.computeVerticalScrollOffset()

This will work for RecyclerViews containing cells of the same height (for vertical scroll offset) and the same width (for horizontal scroll offset)