Android Creating a simple Behavior


To create a Behavior just extend the CoordinatorLayout.Behavior class.

Extend the CoordinatorLayout.Behavior


public class MyBehavior<V extends View> extends CoordinatorLayout.Behavior<V> {

       * Default constructor.
      public MyBehavior() {
       * Default constructor for inflating a MyBehavior from layout.
       * @param context The {@link Context}.
       * @param attrs The {@link AttributeSet}.
      public MyBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);

This behavior need to be attached to a child View of a CoordinatorLayout to be called.

Attach a Behavior programmatically

MyBehavior myBehavior = new MyBehavior();
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) view.getLayoutParams();

Attach a Behavior in XML

You can use the layout_behavior attribute to attach the behavior in XML:

  app:layout_behavior=".MyBehavior" />

Attach a Behavior automatically

If you are working with a custom view you can attach the behavior using the @CoordinatorLayout.DefaultBehavior annotation:

public class MyView extends ..... {