簡體   English   中英

在ViewPager中的所有片段之間同步ScrollView的Scroll位置

[英]Synchronize Scroll position of ScrollView across all fragments inside ViewPager

所以我有一個帶有視圖尋呼機的活動,它會膨脹大約7個碎片,每個碎片里面都有一個ScrollView,我想同步所有7個滾動視圖的滾動,所以如果用戶滾動到碎片3上的一個位置並繼續片段5它們應該位於完全相同的位置,滾動視圖會使相同的子節點膨脹,因此在所有7個片段中,scrollview的總高度是恆定的。

我去某種系統工作,但是它的類型是一個命中或未命中,我得到一個列表的滾動位置並廣播位置和空閑的片段消耗廣播,我也保存在活動上的位置,以便可以在尚未充氣的片段的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;
        }
    }
};

我想知道是否有更好,更穩定的方式來實現類似的東西。

提前致謝。

不確定這個解決方案有多優雅,但它應該可以解決問題。 擴展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);
}

我的自定義ViewPagerNestedScrollView並且兩個子片段都沒有包含任何其他ScrollView

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM