CoordinatorLayout.Behavior 个人小结
来源:10-4 ViewAnchorBehavior接管布局2

慕慕6500093
2022-11-30
CoordinatorLayout.Behavior 概述
Interaction behavior plugin for child views of CoordinatorLayout.
Behavior是CoordinatorLayout子视图的交互行为插件。
A Behavior implements one or more interactions that a user can take on a child view. These interactions may include drags, swipes, flings, or any other gestures.
Behavior实现了一个或多个用户可以在子视图上进行的交互。这些交互可能包括拖拽、滑动、投掷或任何其他手势。
- **1.boolean layoutDependsOn(CoordinatorLayout parent, V child,View dependency) **
Determine whether the supplied child view has another specific sibling view as a layout dependency.
确定提供的子视图是否具有另一个特定的同级视图作为布局依赖项。
This method will be called at least once in response to a layout request.
此方法将在响应布局请求时至少调用一次。
参数说明:child --目标view
dependency – 所依赖的view
返回:如果目标view的布局取决于依赖项dependency的布局,则为true,否则为false。
- 2. onMeasureChild
从Behavior源码可以看出,如果Behavior存在且onMeasureChild返回为true,则不会再调用child(也就是目标view)的onMeasureChild方法来测量大小了:
final Behavior b = lp.getBehavior();
if (b == null || !b.onMeasureChild(this, child, childWidthMeasureSpec, keylineWidthUsed,
childHeightMeasureSpec, 0)) {
onMeasureChild(child, childWidthMeasureSpec, keylineWidthUsed,
childHeightMeasureSpec, 0);
}
参数说明:child --目标 View
widthUsed – 水平方向的可用空间
heightUsed–垂直方向的可用空间(尽管使用的是Used 已使用空间,但剩下的不就是留给目标view的可用空间了嘛,我是这么理解的)
视频代码中的heightUsed分析:
heightUsed: extra space that has been used up by the parent vertically
(possibly by other children of the parent)
父级垂直占用的额外空间(可能被父级的其他子级占用)
个人理解:就是CoordinatorLayout的可用空间,如:A依赖B(anchorId), 那么A可用垂直空间则是:
B的bottom + A的marginTop + 底部高度(如这里的底部互动区高度 48dp)
而widthUsed就更好理解了,没别的view占用水平空间,所以剩下的都是A的(可用空间)。
- 3. onLayoutChild
同理:如果Behavior存在且onLayoutChild返回为true,也不会再调用child(也就是目标view)的onLayoutChild方法来测量摆放位置了
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final Behavior behavior = lp.getBehavior();
if (behavior == null || !behavior.onLayoutChild(this, child, layoutDirection)) {
onLayoutChild(child, layoutDirection);
}
视频代码中的onLayoutChild分析:
// 先layoutChildWithAnchor--> child.layout(childRect.left, childRect.top, childRect.right, childRect.bottom);
parent.onLayoutChild(child, layoutDirection)
// 再让目标view 向下偏移(B的bottom + A的marginTop)--负数就向上偏移,因为屏幕坐标的原因。
child.offsetTopAndBottom(anchorView.bottom + layoutParams.topMargin)
总结:CoordinatorLayout通过Behavior来接管自身的onMeasureChild、onLayoutChild方法的行为,来实现对锚anchor(固定桩)的交互,达到“用已知来辅助未知”的目的。
写回答
1回答
-
LovelyChubby
2022-12-01
恭喜你已经领悟真滴,掌握精髓了,成功进入高阶梯队。如果有进一步提升的想法,可以考虑下老师的另一门课程《移动端架构师体系课》00
相似问题