You can use the [CoordinatorLayout.Behavior](<https://developer.android.com/reference/android/support/design/widget/CoordinatorLayout.Behavior.html>)
to create dependencies between views. You can anchor a View
to another View
by:
[layout_anchor](<https://developer.android.com/reference/android/support/design/widget/CoordinatorLayout.LayoutParams.html#getAnchorId()>)
attribute.Behavior
and implementing the [layoutDependsOn](<https://developer.android.com/reference/android/support/design/widget/CoordinatorLayout.Behavior.html#layoutDependsOn(android.support.design.widget.CoordinatorLayout,%20V,%20android.view.View)>)
method returning true
.For example, in order to create a Behavior
for moving an ImageView
when another one is moved (example Toolbar), perform the following steps:
public class MyBehavior extends CoordinatorLayout.Behavior<ImageView> {...}
[layoutDependsOn](<https://developer.android.com/reference/android/support/design/widget/CoordinatorLayout.Behavior.html#layoutDependsOn(android.support.design.widget.CoordinatorLayout,%20V,%20android.view.View)>)
method returning true
. This method is called every time a change occurs to the layout:@Override
public boolean layoutDependsOn(CoordinatorLayout parent,
ImageView child, View dependency) {
// Returns true to add a dependency.
return dependency instanceof Toolbar;
}
[layoutDependsOn](<https://developer.android.com/reference/android/support/design/widget/CoordinatorLayout.Behavior.html#layoutDependsOn(android.support.design.widget.CoordinatorLayout,%20V,%20android.view.View)>)
returns true
the method [onDependentViewChanged](<https://developer.android.com/reference/android/support/design/widget/CoordinatorLayout.Behavior.html#onDependentViewChanged(android.support.design.widget.CoordinatorLayout,%20V,%20android.view.View)>)
is called:@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);
}