Synchronise ScrollView scroll positions - android

前端 未结 4 2134
误落风尘
误落风尘 2020-11-22 07:05

I have 2 ScrollViews in my android layout. How can I synchronise their scroll positions?

4条回答
  •  忘掉有多难
    2020-11-22 07:39

    An improvement to Andy's solution : In his code, he uses scrollTo, the issue is, if you fling one scrollview in one direction and then fling another one in another direction, you'll notice that the first one doesn't stop his previous fling movement.

    This is due to the fact that scrollView uses computeScroll() to do it's flinging gestures, and it enters in conflict with scrollTo.

    In order to prevent this, just program the onScrollChanged this way :

        public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
        if(interceptScroll){
            interceptScroll=false;
            if(scrollView == scrollView1) {
                scrollView2.onOverScrolled(x,y,true,true);
            } else if(scrollView == scrollView2) {
                scrollView1.onOverScrolled(x,y,true,true);
            }
            interceptScroll=true;
        }
    }
    

    with interceptScroll a static boolean initialized to true. (this helps avoid infinite loops on ScrollChanged)

    onOverScrolled is the only function I found that could be used to stop the scrollView from flinging (but there might be others I've missed !)

    In order to access this function (which is protected) you have to add this to your ObservableScrollViewer

    public void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) {
        super.onOverScrolled(scrollX, scrollY, clampedX, clampedY);
    }
    

提交回复
热议问题