在视图之间创建依赖关系
你可以使用 CoordinatorLayout.Behavior 在视图之间创建依赖关系。你可以通过以下方式将 View 锚定到另一个 View:
- 使用 layout_anchor属性。
- 创建一个自定义 Behavior并实现layoutDependsOn方法返回true。
例如,为了创建 Behavior 以在移动另一个时移动 ImageView(示例工具栏),请执行以下步骤:
- 
创建自定义行为 : public class MyBehavior extends CoordinatorLayout.Behavior<ImageView> {...}
- 
重写 layoutDependsOn方法返回true。每次布局发生更改时都会调用此方法:@Override public boolean layoutDependsOn(CoordinatorLayout parent, ImageView child, View dependency) { // Returns true to add a dependency. return dependency instanceof Toolbar; }
- 
每当方法 layoutDependsOn返回true时,方法onDependentViewChanged被调用:@Override public boolean onDependentViewChanged(CoordinatorLayout parent, ImageView child, View dependency) { // Implement here animations, translations, or movements; always related to the provided dependency. float translationY = Math.min(0, dependency.getTranslationY() - dependency.getHeight()); child.setTranslationY(translationY); }