Synchronize ScrollView scroll position across all fragments inside ViewPager

So, I have activity with a presentation pager that inflates about 7 fragments, and each fragment has a ScrollView inside it, I want to synchronize the scrolling of all 7 scrollviews, so if the user scrolls to the position on fragment 3 and goes to fragment 5, they should being in the same position, the same children inflate scrollviews, so the total scroll height is constant in all 7 fragments.

I start some kind of system, but its kind of hit or miss, I get the scroll position of the list and translate the position, and the fragment that is idle consumes the translation, and I keep the position in action so that the position can be requested in onResume fragments that are still were not inflated. Here is my code:

@Override public void onResume() { super.onResume(); mParentScrollView.setScrollY(mParentActivity.getScrollPos()); } @Override public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldX, int oldY) { mScrollListener.onScroll(y); mParentActivity.setScrollPos(y); if (callbackSwitch) { Intent intent = new Intent("ACTION_SCROLL"); intent.putExtra("TRANSLATION", y); LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent); } callbackSwitch = true; //Switch to stop recursive calls } private BroadcastReceiver mTranslationReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (!isVisible) { int translation = intent.getIntExtra("TRANSLATION", 0); mParentScrollView.setScrollY(translation); callbackSwitch = false; } } }; 

I wanted to know if there is a better and more stable way to achieve something like this.

Thanks at Advance.

+4
source share
1 answer

Not sure how elegant these decisions are, but he has to do the trick. Extend ViewPager and override the onMeasure(int, int) method.

 @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int height = 0; for (int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); int h = child.getMeasuredHeight(); if (h > height) height = h; } heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } 

My custom ViewPager was inside NestedScrollView , and both child fragments did not contain extra ScrollView s.

0
source

All Articles