Android CoordinatorLayout and Behaviors Create dependencies between Views

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

You can use the CoordinatorLayout.Behavior to create dependencies between views. You can anchor a View to another View by:

For example, in order to create a Behavior for moving an ImageView when another one is moved (example Toolbar), perform the following steps:

  • Create the custom Behavior:

    public class MyBehavior extends CoordinatorLayout.Behavior<ImageView> {...}
    
  • Override the layoutDependsOn 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;
    }
    
  • Whenever the method layoutDependsOn returns true the method onDependentViewChanged 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);
    }
    


Got any Android Question?