I need to synchronize the scrolling positions of two ScrollViews
.
Both ScrollViews
contain their individual RecyclerView
(I can't put them inside same ScrollView due to design requirements).
How can I achieve that?
I need to synchronize the scrolling positions of two ScrollViews
.
Both ScrollViews
contain their individual RecyclerView
(I can't put them inside same ScrollView due to design requirements).
How can I achieve that?
I highly recommend that you CHANGE YOUR DESIGN but there is a way to achieve this
for first scroll view, define two variable x,y and get current scroll position
x = firstScrollView.getScrollX();
y = firstScrollView.getScrollY();
and pass these values to other scrollView "scrollTo" method.
like:
ScrollView secondScrollView = (ScrollView)findViewById(R.id.scrollView);
secondScrollView.scrollTo(x, y);
if didn't work try:
secondScrollView.post(new Runnable() {
@Override
public void run() {
secondScrollView.scrollTo(x, y);
}
});
First of all, use NestedScrollView
from Support library since it enables us to listen scroll events easily. Then, set onScrollChange
listeners for both NestedScrollView
you have. When you receive scroll change for scrollView1
for instance, call scrollTo(...)
for scrollView2
:
scrollView1.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
@Override
public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
scrollView2.setOnScrollChangeListener(null);
scrollView2.scrollTo(scrollX, scrollY);
scrollView2.setOnScrollChangeListener(...); //SET SCROLL LISTENER AGAIN
}
});
Before calling scrollTo(..)
for scrollView2
, remove its listener, then add it again. Otherwise, scrollTo(..)
you call can cause infinite calls in both listeners of NestedScrollView
s.
And of course, you need to write similar above code for your scrollView2
.
Attach an RecyclerView.OnScrollListener
to both RecyclerViews
via addOnScrollListener(RecyclerView.OnScrollListener listener)
.
Update the position of the other one when the event is fired via: scrollTo(int x, int y)
.
Remember to somehow distinguish between a user-triggered scroll and a programmtic scroll (from the other RecyclerViews
event).
One way would be, like Ugurcan Yildirim suggested, to detach the listener of the ScrollView
you want to update.
Another option is a boolean flag isUserTriggered
. A third way would be to determine which ScrollView currently has the focus to distinguish (see here).