I have created a activity Webview content placed in Recyclerview. I want to get the scroll Y position when I scroll webview. I tried Webview.getScrollY(), Webview.getY(), RecyclerView.getScrollY(), RecyclerView.getY(),... but it do not work fine. I can't get current scroll Y. Is there any suggest for get scroll Y of Webview or RecyclerView ?
2 Answers
Use a RecyclerView.OnScrollListener for the RecyclerView and a View.OnScrollChangeListener for the webview.
You'll have to keep track of the total scroll yourself, like this:
private int mTotalScrolled = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ... recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); mTotalScrolled += dy; } }); ... } private int getScrollForRecycler(){ return mTotalScrolled; } 8 Comments
Sinh Phan
I've tried
RecyclerView.OnScrollListener. But onScrolled(RecyclerView recyclerView, int dx, int dy) method in this just get dy not y position.Xavier.S
Yes, it is right, but partially. When I use
linearLayoutManager.scrollToPositionWithOffset(int, int) to manually change the position, I can't get the delta Y, namely dy is always 0 during this process. So I regard it not reliable enough and need a better way.Pkmmte
recyclerView.computeVerticalScrollOffset() would be a better answer than this.Saket
Not really.
computeVerticalScrollOffset() isn't the same as the number of pixels scrolled. RV uses it for showing a scrollbar and it's value is very imprecise.StarterPack
this runs into issues when using notifyItemRemoved in the adapter since the removed item causes mTotalScrolled to change without calling onScroll
|
computeVerticalScrollOffset()is more convenient at this situation as @Pkmmte mentioned.
mTotalScrolled = recyclerView.computeVerticalScrollOffset(); 1 Comment
RadekJ
it doesn't return scrollY of recycler, it returns The vertical offset of the scrollbar's thumb
view.computeVerticalScrollOffset()