Android – synchronizes the scroll position of the Scrollview between all clips in the viewpager
Therefore, I have an activity with a view pager. It will expand about 7 fragments. There is a Scrollview in each fragment. I want to synchronize the scrolling of all 7 scrolling views. Therefore, if the user scrolls to a position on fragment 3 and continues fragment 5, they should be in the same position. The scrolling view will expand the same child nodes. Therefore, in all 7 fragments, The total height of the Scrollview is constant
I work in a certain system, but its type is a hit or miss. I get the scroll position of a list and broadcast the position and idle fragment consumption broadcast. I also save the position on the activity so that I can request the position in the onresume of the fragment that has not been inflated. This 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 wonder if there is a better and more stable way to achieve something similar
Thank you in advance
resolvent:
I'm not sure how elegant this solution is, but it should solve the problem. Extend viewpager and override 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 is in nestedscrollview, and neither of the two sub fragments contains any other Scrollview