AppBarLayout 不滚动问题
起因#
由于项目App迭代,一个布局发生了改变。因此产生了一个奇怪的问题,按道理,滑动NestedScrollView
的时候,AppBarLayout
会上移。这是appbar_scrolling_view_behavior
和scroll|enterAlwaysCollapsed
使用的常规操作嘛。但是拖拽ViewPager
里的一个item里的横向RecyclerView
时,AppBarLayout
没有按照预想中的情况上移。布局如下图:
方法调试#
由于AppBarLayout
和CoordinatorLayout
都是库里的,没办法debug,所以增大了问题的难度。于是尝试了这些办法:
- 在自己项目下创建一个和
CoordinatorLayout
同样的包androidx.coordinatorlayout.widget
,将其复制进去 - 由于app模块下代码会覆盖其他模块的代码,所以这样就可以愉快的debug了,但不太好用,debug时间太长会产生ANR
- 在复制出来的类中添加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.Behavior
的onStartNestedScroll
打印的日志,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;
}
CoordinatorLayout
的onStartNestedScroll
的返回值取决于子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
里的,NestedScrollView
的onInterceptTouchEvent
会走,于是NestedScrollView
先上传纵向的嵌套滑动事件,交给CoordinatorLayout
处理,AppBarLayout.Behavior
接受了,紧接着走RecyclerView
的onInterceptTouchEvent
方法,它最终会报告横向滑动事件给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);
}
}
作者:徐影魔
出处:https://www.cnblogs.com/xunevermore/p/16064261.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· NetPad:一个.NET开源、跨平台的C#编辑器
· PowerShell开发游戏 · 打蜜蜂
· 凌晨三点救火实录:Java内存泄漏的七个神坑,你至少踩过三个!