AppBarLayout 不滾動問題


起因

由於項目App迭代,一個布局發生了改變。因此產生了一個奇怪的問題,按道理,滑動NestedScrollView的時候,AppBarLayout會上移。這是appbar_scrolling_view_behaviorscroll|enterAlwaysCollapsed使用的常規操作嘛。但是拖拽ViewPager里的一個item里的橫向RecyclerView時,AppBarLayout沒有按照預想中的情況上移。布局如下圖:
AppBarLayout

方法調試

由於AppBarLayoutCoordinatorLayout都是庫里的,沒辦法debug,所以增大了問題的難度。於是嘗試了這些辦法:

  1. 在自己項目下創建一個和CoordinatorLayout同樣的包androidx.coordinatorlayout.widget,將其復制進去
  2. 由於app模塊下代碼會覆蓋其他模塊的代碼,所以這樣就可以愉快的debug了,但不太好用,debug時間太長會產生ANR
  3. 在復制出來的類中添加log,觀察異常日志

問題探索

這個問題涉及到嵌套滑動和behavior,所以我查看了相關源代碼,大概了解了相關邏輯。
在一次debug中發現CoordinatorLayout的一塊代碼不對勁:

code0

    public void onNestedPreScroll(View target, int dx, int dy, int[] consumed, int type) {
        int xConsumed = 0;
        int yConsumed = 0;
        boolean accepted = false;

        final int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View view = getChildAt(i);
            if (view.getVisibility() == GONE) {
                // If the child is GONE, skip...
                continue;
            }

            final LayoutParams lp = (LayoutParams) view.getLayoutParams();
            Behavior behavior = lp.getBehavior();
            boolean nestedScrollAccepted = lp.isNestedScrollAccepted(type);
            if (!nestedScrollAccepted) {//view為AppBarLayout時這里居然通過了
                continue;
            }

            final Behavior viewBehavior = lp.getBehavior();
            if (viewBehavior != null) {
                mBehaviorConsumed[0] = 0;
                mBehaviorConsumed[1] = 0;
                //正常情況AppBarLayout的viewBehavior會被調用
                viewBehavior.onNestedPreScroll(this, view, target, dx, dy, mBehaviorConsumed, type);

                xConsumed = dx > 0 ? Math.max(xConsumed, mBehaviorConsumed[0])
                        : Math.min(xConsumed, mBehaviorConsumed[0]);
                yConsumed = dy > 0 ? Math.max(yConsumed, mBehaviorConsumed[1])
                        : Math.min(yConsumed, mBehaviorConsumed[1]);

                accepted = true;
            }
        }

        consumed[0] = xConsumed;
        consumed[1] = yConsumed;

        if (accepted) {
            onChildViewsChanged(EVENT_NESTED_SCROLL);
        }
    }

由於CoordinatorLayout本身不處理嵌套滑動,而是交給它子布局的Behavior處理,所以上面這個方法的nestedScrollAccepted一定是true。並且AppBarLayout如果要滑動那么它的onNestedPreScroll方法一定會被調用,HeaderBehavior中相關邏輯如下:

code1

   public void onNestedPreScroll(
        CoordinatorLayout coordinatorLayout,
        @NonNull T child,
        View target,
        int dx,
        int dy,
        int[] consumed,
        int type) {
      if (dy != 0) {
        int min;
        int max;
        if (dy < 0) {
          // We're scrolling down
          min = -child.getTotalScrollRange();
          max = min + child.getDownNestedPreScrollRange();
        } else {
          // We're scrolling up
          min = -child.getUpNestedPreScrollRange();
          max = 0;
        }
        if (min != max) {
          //就是這里AppBarLayout的Behavior消費了嵌套滑動的dy
          consumed[1] = scroll(coordinatorLayout, child, dy, min, max);
        }
      }
      if (child.isLiftOnScroll()) {
        child.setLiftedState(child.shouldLift(target));
      }
    }

通過多次嘗試,發現如下可疑日志:

2022-03-27 19:14:57.317 16421-16421/*** I/MyAppBarLayout: onStartNestedScroll: true,nestedScrollAxes:2
2022-03-27 19:14:57.317 16421-16421/*** I/MyAppBarLayout: onNestedScrollAccepted: 2
2022-03-27 19:14:57.318 16421-16421/*** I/MyAppBarLayout: onStartNestedScroll: false,nestedScrollAxes:1

AppBarLayout.Behavior添加的日志

code2

    override fun onStartNestedScroll(
        parent: CoordinatorLayout,
        child: AppBarLayout,
        directTargetChild: View,
        target: View,
        nestedScrollAxes: Int,
        type: Int
    ): Boolean {
        val onStartNestedScroll = super.onStartNestedScroll(
            parent,
            child,
            directTargetChild,
            target,
            nestedScrollAxes,
            type
        )
        Log.i(TAG, "onStartNestedScroll: $onStartNestedScroll,nestedScrollAxes:$nestedScrollAxes")
        return onStartNestedScroll
    }

這是AppBarLayout.BehavioronStartNestedScroll打印的日志,nestedScrollAxes:2為縱向,1為橫向。如果AppBarLayout要滑動,那么onStartNestedScroll一定返回true,因為只有onStartNestedScroll返回true,Behavior后續的onNestedPreScroll才會被回調。可以看到縱向剛返回true,橫向就返回false。

我們再來看CoordinatorLayout的這塊代碼:

code3

    public boolean onStartNestedScroll(View child, View target, int axes, int type) {
        boolean handled = false;
        final int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View view = getChildAt(i);
            if (view.getVisibility() == View.GONE) {
                // If it's GONE, don't dispatch
                continue;
            }
            final LayoutParams lp = (LayoutParams) view.getLayoutParams();
            final Behavior viewBehavior = lp.getBehavior();
            if (viewBehavior != null) {
                final boolean accepted = viewBehavior.onStartNestedScroll(this, view, child,
                        target, axes, type);
                handled |= accepted;
                lp.setNestedScrollAccepted(type, accepted);
                        + viewBehavior.getClass().getSimpleName() + "," + accepted + ",type:" + type);
            } else {
                lp.setNestedScrollAccepted(type, false);
            }
        }
        return handled;
    }

CoordinatorLayoutonStartNestedScroll的返回值取決於子view的behavior,如果behavior處理會在子view(AppBarLayout)CoordinatorLayout.LayoutParams中設置accepted為true。問題來了,剛才我們看到日志縱向true后面跟了個橫向false,而這個方法並沒有區分方向。

code4

        class CoordinatorLayout.LayoutParams
        ...
        void setNestedScrollAccepted(int type, boolean accept) {
            switch (type) {
                case ViewCompat.TYPE_TOUCH:
                    mDidAcceptNestedScrollTouch = accept;
                    break;
                case ViewCompat.TYPE_NON_TOUCH:
                    mDidAcceptNestedScrollNonTouch = accept;
                    break;
            }
        }

於是AppBarLayout.Behavior剛接收了縱向的嵌套滑動返回true,又拒絕了橫向嵌套滑動返回false,對應的CoordinatorLayout.LayoutParams#isNestedScrollAccepted被覆蓋,返回false。code0處nestedScrollAccepted就為false,所以AppBarLayout.Behavior的沒有讓AppBarLayout產生滑動。這與操作的現象是符合的,在縱向滑動RecyclerView時,AppBarLayout沒有動。

原因分析

RecyclerView也支持嵌套滑動。這里補充一點startNestedScroll是由NestedScrollingChildHelper實現的,它會將嵌套滑動上傳,也就是NestedScrollingChild都會將嵌套滑動先交給NestedScrollingParent處理。
看下面代碼,發現會將橫向縱向的嵌套滑動事件

code5

  class RecyclerView
  ...
     public boolean onInterceptTouchEvent(MotionEvent e) {
        if (mLayoutSuppressed) {
            // When layout is suppressed,  RV does not intercept the motion event.
            // A child view e.g. a button may still get the click.
            return false;
        }

        // Clear the active onInterceptTouchListener.  None should be set at this time, and if one
        // is, it's because some other code didn't follow the standard contract.
        mInterceptingOnItemTouchListener = null;
        if (findInterceptingOnItemTouchListener(e)) {
            cancelScroll();
            return true;
        }

        if (mLayout == null) {
            return false;
        }

        final boolean canScrollHorizontally = mLayout.canScrollHorizontally();
        final boolean canScrollVertically = mLayout.canScrollVertically();

        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain();
        }
        mVelocityTracker.addMovement(e);

        final int action = e.getActionMasked();
        final int actionIndex = e.getActionIndex();

        switch (action) {
            case MotionEvent.ACTION_DOWN:
                if (mIgnoreMotionEventTillDown) {
                    mIgnoreMotionEventTillDown = false;
                }
                mScrollPointerId = e.getPointerId(0);
                mInitialTouchX = mLastTouchX = (int) (e.getX() + 0.5f);
                mInitialTouchY = mLastTouchY = (int) (e.getY() + 0.5f);

                if (mScrollState == SCROLL_STATE_SETTLING) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                    setScrollState(SCROLL_STATE_DRAGGING);
                    stopNestedScroll(TYPE_NON_TOUCH);
                }

                // Clear the nested offsets
                mNestedOffsets[0] = mNestedOffsets[1] = 0;

                int nestedScrollAxis = ViewCompat.SCROLL_AXIS_NONE;
                if (canScrollHorizontally) {
                    nestedScrollAxis |= ViewCompat.SCROLL_AXIS_HORIZONTAL;
                }
                if (canScrollVertically) {
                    nestedScrollAxis |= ViewCompat.SCROLL_AXIS_VERTICAL;
                }
                startNestedScroll(nestedScrollAxis, TYPE_TOUCH);
                break;

                ...
        return mScrollState == SCROLL_STATE_DRAGGING;
    }

這里RecyclerView的mLayout是橫向的,最終CoordinatorLayout分發的時候AppBarLayout.Behavior沒有處理,而RecyclerView是在NestedScrollViw里的,NestedScrollViewonInterceptTouchEvent會走,於是NestedScrollView先上傳縱向的嵌套滑動事件,交給CoordinatorLayout處理,AppBarLayout.Behavior接受了,緊接着走RecyclerViewonInterceptTouchEvent方法,它最終會報告橫向滑動事件給CoordinatorLayout(這里會經過NestedScrollView,但是它沒處理),而CoordinatorLayout在分發橫向嵌套滑動的時候,AppBarLayout.Behavior又拒絕了。一切來得太快,AppBarLayout.Behavior出爾反爾。

解決方法

public class MyCoordinatorLayout extends CoordinatorLayout {
    public MyCoordinatorLayout(@NonNull Context context) {
        super(context);
    }

    public MyCoordinatorLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public MyCoordinatorLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onStartNestedScroll(View child, View target, int axes, int type) {
        if ((axes & ViewCompat.SCROLL_AXIS_HORIZONTAL) != 0) {
            //不處理橫向嵌套滑動事件
            return false;
        }
        return super.onStartNestedScroll(child, target, axes, type);
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM