【问题标题】:Synchronize Scroll position of ScrollView across all fragments inside ViewPager在 ViewPager 内的所有片段中同步 ScrollView 的滚动位置
【发布时间】:2015-08-12 20:14:03
【问题描述】:

所以我有一个带有视图寻呼机的活动,它膨胀了大约 7 个片段,并且每个片段里面都有一个 ScrollView,我想同步所有 7 个滚动视图的滚动,所以如果用户滚动到片段 3 上的某个位置并且移动到片段 5,它们应该在完全相同的位置,滚动视图膨胀相同的子级,因此滚动视图的总高度在所有 7 个片段中是恒定的。

我去某种系统工作,但它的一种命中或错过,我得到一个列表的滚动位置并广播该位置,空闲的片段消耗广播,我将位置保存在活动中也可以在尚未膨胀的片段的 onResume 中请求该位置。这是我的代码:

@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;
        }
    }
};

我想知道是否有更好更稳定的方法来实现类似的目标。

提前致谢。

【问题讨论】:

    标签: android android-fragments android-viewpager scrollview


    【解决方案1】:

    不确定这个解决方案有多优雅,但它应该可以解决问题。扩展ViewPager 并覆盖onMeasure(int, int) 方法。

    @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);
    }
    

    我的自定义 ViewPager 位于 NestedScrollView 内,两个子片段没有包含任何额外的 ScrollViews。

    【讨论】:

      猜你喜欢
      • 2023-04-08
      • 2011-04-26
      • 1970-01-01
      • 2015-05-25
      • 1970-01-01
      • 1970-01-01
      • 2015-10-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多