Stack Overflow archive
2 scoreaccepted

Scrolling parallel views simultaneously

score
2
question views
711
license
CC BY-SA 3.0

Hopefully I understand your question correctly. If you want both ScrollViews to scroll simultaneously then the code below should do the trick (untested):

First create an interface to listen to scroll events:

java
public interface ScrollChangeListener {

    public void onScrollChanged(View view, int x, int y, int oldx, int oldy);
}

Next, create a custom view so you can listen for scroll changes:

java
public class ObservableScrollView extends ScrollView {

    private ScrollChangeListener mScrollChangeListener;

    public ObservableScrollView(Context context) {
        super(context);
    }

    public ObservableScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ObservableScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public ObservableScrollView(Context context, AttributeSet attrs, int defStyleAttr,
                                int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    public void setScrollChangeListener(ScrollChangeListener listener) {
        mScrollChangeListener = listener;
    }

    @Override
    protected void onScrollChanged(int x, int y, int oldx, int oldy) {
        if (mScrollChangeListener != null) {
            mScrollChangeListener.onScrollChanged(this, x, y, oldx, oldy);
        }
    }
}

Use your custom view and create a listener for both ScrollViews.

java
ObservableScrollView mScrollView1;

ObservableScrollView mScrollView2;

...

ScrollChangeListener listener = new ScrollChangeListener() {

    @Override
    public void onScrollChanged(View view, int x, int y, int oldx, int oldy) {
        ScrollView scrollView;
        if (view == mScrollView1) {
            scrollView = mScrollView2;
        } else if (view == mScrollView2) {
            scrollView = mScrollView1;
        } else {
            return;
        }
        scrollView.scrollTo(x, y);
    }
};

...

mScrollView1.setScrollChangeListener(listener);
mScrollView2.setScrollChangeListener(listener);

Originally posted on Stack Overflow. Public user contributions are licensed under Creative Commons Attribution-ShareAlike.