Android tip #028 – Sync two ScrollLayouts when scroll
Platform/Language: Java/XML/Android
Description: if we need to scroll two ScrollLayouts at the same time we can create a new View that implements the standard ScrollView in order to create a listener which allow us to know when this one is scrolling and modify the behavior of the other (or maybe because we want to know about the scroll behavior).
Code:
IScrollListener.java
1 2 3 4 5 6 7 | public interface IScrollListener { void onScrollChanged( IScrollListener scrollView, int x, int y, int oldx, int oldy); } |
ObservableScrollView.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | public class ObservableScrollView extends ScrollView { private IScrollListener listener = null; public ObservableScrollView(Context context) { super(context); } public ObservableScrollView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public ObservableScrollView(Context context, AttributeSet attrs) { super(context, attrs); } public void setScrollViewListener(IScrollListener listener) { this.listener = listener; } @Override protected void onScrollChanged(int x, int y, int oldx, int oldy) { super.onScrollChanged(x, y, oldx, oldy); if (listener != null) { listener.onScrollChanged(this, x, y, oldx, oldy); } } } |
Use two ObservableScrollView in your layout: oScrollViewOne, oScrollViewTwo.
YoutActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | public class YourActivity extends Activity implements ScrollViewListener { ObservableScrollView oScrollViewOne, oScrollViewTwo; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); oScrollViewOne = (ObservableScrollView) this .findViewById(R.id.oScrollViewOne); oScrollViewTwo = (ObservableScrollView) this .findViewById(R.id.oScrollViewTwo); oScrollViewOne.setScrollViewListener(this); oScrollViewTwo.setScrollViewListener(this); } @Override void onScrollChanged( IScrollListener scrollView, int x, int y, int oldx, int oldy) { if (scrollView == oScrollViewOne) { oScrollViewTwo.scrollTo(x, y); } else if (scrollView == oScrollViewTwo) { oScrollViewOne.scrollTo(x, y); } } } |

