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()
returns0
(docs say: initial scroll value)- the
LayoutManager
hasfindFirstVisibleItemPosition
, 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);
}
});
RecyclerView already have method to get horizontal and vertical scroll offset
This will work for RecyclerViews containing cells of the same height (for vertical scroll offset) and the same width (for horizontal scroll offset)
Thanks to @umar-qureshi for the right lead! It appears that you can determine the scroll percentage with
Offset
,Extent
, andRange
such thatFor example (to be put in an
OnScrollListener
):Than where you need to get the offset:
by override RecyclerView
onScrolled(int dx,int dy)
, you can get the scroll offset. but when you add or remove the item, the value may be wrong.If you need to know the current page and its offset in comparison to the width of RecyclerView you may wanna try something like this:
If
currentPage
has index 0 thenleftIndicator
(arrow) will be transparent, and so will be andrightIndicator
if there's only onepage
(in the example, the adapter always has at least one item to show so there's no check for the empty value).This way you will basically have almost the same functionality as if you have been using the callback
pageScrolled
fromViewPager.OnPageChangeListener
.Solution 1:
setOnScrollListener
Save your X-Position as class variable and update each change within the
onScrollListener
. Ensure you don't resetoverallXScroll
(f.e.onScreenRotationChange
)Solution 2: Calculate current position.
In my case, I have a horizontal List which is filled with time values (0:00, 0:30, 1:00, 1:30 ... 23:00, 23:30). I'm calculating the time from the time-item, which is in the middle of the screen (calculation point). That's why I need the exact X-Scroll Position of my
RecycleView
First item (Header item) has an extra padding, to set 0min to the center
}