iroyo iroyo - 1 month ago 11
Android Question

Quirk with custom Layout Behavior when updating to Support Library 24

In the last couple of project I've worked on I always had a custom layout behavior for a Button to mimick the animation a FloatingButton makes when a Snackbar is shown. The code I used is:

public class BehaviorButton extends CoordinatorLayout.Behavior<Button> {

public BehaviorButton(Context context, AttributeSet attrs) {}

@Override
public boolean layoutDependsOn(CoordinatorLayout parent, Button child, View dependency) {
return dependency instanceof Snackbar.SnackbarLayout;
}

@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, Button child, View dependency) {
float translationY = Math.min(0, dependency.getTranslationY() - dependency.getHeight());
child.setTranslationY(translationY);
return true;
}
}


And then "bind" this class to the Button through xml.

app:layout_behavior=".BehaviorButton"


Nothing special. The problem: When I updated the support libraries from 23.4.0 to 24 this functionality disappeared. My question is: How am I supposed to implement such behavior in support library 24?

Correct behavior with 23.4.0

In the following gif you can see how there is NO Button. When I add the
layout_behavior
it "loses" its postion.

Button disappear!!

Answer

You need to check if the dependency is SnackbarLayout and only then translate the button.

@Override
    public boolean onDependentViewChanged(CoordinatorLayout parent, Button child, View dependency) {
      if(dependency instanceof Snackbar.SnackbarLayout){
        float translationY = Math.min(0, dependency.getTranslationY() - dependency.getHeight());
        child.setTranslationY(translationY);
        return true;
       }
      return false;
    }