记录一个AppBarLayout的bugfix修复

问题现象: CoordinatorLayout嵌套 上半部分AppBarLayout+下半部分RecyclerView, 对下半部分RecyclerView的显示隐藏做操作(如吟唱recyclerView展示一个ErrorLayout or EmptyLayout, 会导致AppBarLayout区域不再响应滑动, 这个bug较容易忽略, 因为滑动界面上的下半部分立即可以恢复滑动使现象消失.

这个问题是由系统源码导致, 里记录一下原因分析:

从CoordinatorLayout看起:

HeaderBehavior:

AppBarlayout:

lastNestedScrollingChildRef的赋值只有两处,

less 复制代码
@Override
public boolean onStartNestedScroll(
    @NonNull CoordinatorLayout parent,
    @NonNull T child,
    @NonNull View directTargetChild,
    View target,
    int nestedScrollAxes,
    int type) {
  //省略...
  // A new nested scroll has started so clear out the previous ref
  lastNestedScrollingChildRef = null;
  //省略...
  return started;
}

@Override
public void onStopNestedScroll(
    CoordinatorLayout coordinatorLayout, @NonNull T abl, View target, int type) {

  //省略... 
  // Keep a reference to the previous nested scrolling child
  lastNestedScrollingChildRef = new WeakReference<>(target);
}

所以lastNestedScrollingChildRef得含义和名字一样, 是上一次的嵌套滚动view, 如果我们滑动了RecyclerView, 那么这个值就是RecyclerView, 如果此时把RecyclerView隐藏, 再滑动AppBarLayout区域, 就会滑不动了, 因为AppBarLayout中CanDragView中判断RecyclerView isShown()为false.

为什么滑动一下AppBarLayout下面的错误界面或空界面区域就会恢复呢? 因为在View中有如下一段代码:

scss 复制代码
public boolean dispatchTouchEvent(MotionEvent event) {
    //...
    final int actionMasked = event.getActionMasked();
    if (actionMasked == MotionEvent.ACTION_DOWN) {
        // Defensive cleanup for new gesture
        stopNestedScroll();
    }
    //...

由前面源码得知, stopNestedScroll();中会对lastNestedScrollingChildRef重新赋值. 这也是为什么是在 lastNestedScrollingChildRef是在stopNestedScroll();中赋值, 而每次开始滑动是lastNestedScrollingChildRef总是不为空.

至此, AppBarLayout偶现滑不动的原因就清楚了.

相关推荐
用户20187928316722 分钟前
强制关闭生命周期延时的Activity实现思路
android
用户20187928316737 分钟前
Activity后生命周期暂停问题
android
用户20187928316737 分钟前
浅析:WindowManager添加的 View 的事件传递机制
android
顾林海39 分钟前
从"面条代码"到"精装别墅":Android MVPS架构的逆袭之路
android·面试·架构
白夜1 小时前
Android 开发工程常识
android
编程乐学2 小时前
原创模板--基于 Android 开发的驾考训练App
android·android studio·大作业·移动端开发·安卓移动开发·驾考宝典·驾考app
阿赵3D2 小时前
Unity2022打包安卓报错的奇葩问题
android·unity·安卓
aqiu~7 小时前
Android Studio受难记
android·android studio
安卓开发者8 小时前
Android中RxJava与LiveData的结合使用
android·echarts·rxjava