jjzjj

AppBarLayout 不滚动问题

为往圣而继绝学 2023-03-28 原文

起因

由于项目App迭代,一个布局发生了改变。因此产生了一个奇怪的问题,按道理,滑动NestedScrollView的时候,AppBarLayout会上移。这是appbar_scrolling_view_behaviorscroll|enterAlwaysCollapsed使用的常规操作嘛。但是拖拽ViewPager里的一个item里的横向RecyclerView时,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);
    }
}

有关AppBarLayout 不滚动问题的更多相关文章

  1. ruby - 在 64 位 Snow Leopard 上使用 rvm、postgres 9.0、ruby 1.9.2-p136 安装 pg gem 时出现问题 - 2

    我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po

  2. ruby - 通过 rvm 升级 ruby​​gems 的问题 - 2

    尝试通过RVM将RubyGems升级到版本1.8.10并出现此错误:$rvmrubygemslatestRemovingoldRubygemsfiles...Installingrubygems-1.8.10forruby-1.9.2-p180...ERROR:Errorrunning'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/rub

  3. ruby - 通过 RVM (OSX Mountain Lion) 安装 Ruby 2.0.0-p247 时遇到问题 - 2

    我的最终目标是安装当前版本的RubyonRails。我在OSXMountainLion上运行。到目前为止,这是我的过程:已安装的RVM$\curl-Lhttps://get.rvm.io|bash-sstable检查已知(我假设已批准)安装$rvmlistknown我看到当前的稳定版本可用[ruby-]2.0.0[-p247]输入命令安装$rvminstall2.0.0-p247注意:我也试过这些安装命令$rvminstallruby-2.0.0-p247$rvminstallruby=2.0.0-p247我很快就无处可去了。结果:$rvminstall2.0.0-p247Search

  4. ruby - Fast-stemmer 安装问题 - 2

    由于fast-stemmer的问题,我很难安装我想要的任何ruby​​gem。我把我得到的错误放在下面。Buildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingfast-stemmer:ERROR:Failedtobuildgemnativeextension./System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/rubyextconf.rbcreatingMakefilemake"DESTDIR="cleanmake"DESTDIR=

  5. ruby - 安装 Ruby 时遇到问题(无法下载资源 "readline--patch") - 2

    当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub

  6. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  7. ruby-on-rails - 简单的 Ruby on Rails 问题——如何将评论附加到用户和文章? - 2

    我意识到这可能是一个非常基本的问题,但我现在已经花了几天时间回过头来解决这个问题,但出于某种原因,Google就是没有帮助我。(我认为部分问题在于我是一个初学者,我不知道该问什么......)我也看过O'Reilly的RubyCookbook和RailsAPI,但我仍然停留在这个问题上.我找到了一些关于多态关系的信息,但它似乎不是我需要的(尽管如果我错了请告诉我)。我正在尝试调整MichaelHartl'stutorial创建一个包含用户、文章和评论的博客应用程序(不使用脚手架)。我希望评论既属于用户又属于文章。我的主要问题是:我不知道如何将当前文章的ID放入评论Controller。

  8. 【高数】用拉格朗日中值定理解决极限问题 - 2

    首先回顾一下拉格朗日定理的内容:函数f(x)是在闭区间[a,b]上连续、开区间(a,b)上可导的函数,那么至少存在一个,使得:通过这个表达式我们可以知道,f(x)是函数的主体,a和b可以看作是主体函数f(x)中所取的两个值。那么可以有,  也就意味着我们可以用来替换 这种替换可以用在求某些多项式差的极限中。方法: 外层函数f(x)是一致的,并且h(x)和g(x)是等价无穷小。此时,利用拉格朗日定理,将原式替换为 ,再进行求解,往往会省去复合函数求极限的很多麻烦。使用要注意:1.要先找到主体函数f(x),即外层函数必须相同。2.f(x)找到后,复合部分是等价无穷小。3.要满足作差的形式。如果是加

  9. SPI接收数据异常问题总结 - 2

    SPI接收数据左移一位问题目录SPI接收数据左移一位问题一、问题描述二、问题分析三、探究原理四、经验总结最近在工作在学习调试SPI的过程中遇到一个问题——接收数据整体向左移了一位(1bit)。SPI数据收发是数据交换,因此接收数据时从第二个字节开始才是有效数据,也就是数据整体向右移一个字节(1byte)。请教前辈之后也没有得到解决,通过在网上查阅前人经验终于解决问题,所以写一个避坑经验总结。实际背景:MCU与一款芯片使用spi通信,MCU作为主机,芯片作为从机。这款芯片采用的是它规定的六线SPI,多了两根线:RDY和INT,这样从机就可以主动请求主机给主机发送数据了。一、问题描述根据从机芯片手

  10. git使用常见问题(提交代码,合并冲突) - 2

    文章目录git常用命令(简介,详细参数往下看)Git提交代码步骤gitpullgitstatusgitaddgitcommitgitpushgit代码冲突合并问题方法一:放弃本地代码方法二:合并代码常用命令以及详细参数gitadd将文件添加到仓库:gitdiff比较文件异同gitlog查看历史记录gitreset代码回滚版本库相关操作远程仓库相关操作分支相关操作创建分支查看分支:gitbranch合并分支:gitmerge删除分支:gitbranch-ddev查看分支合并图:gitlog–graph–pretty=oneline–abbrev-commit撤消某次提交git用户名密码相关配置g

随机推荐