The SwipeDismissBehavior(opens new window) works on any View and implements the functionality of swipe to dismiss in our layouts with a CoordinatorLayout.
Just use:
final SwipeDismissBehavior<MyView> swipe = new SwipeDismissBehavior();
//Sets the swipe direction for this behavior.
swipe.setSwipeDirection(
SwipeDismissBehavior.SWIPE_DIRECTION_ANY);
//Set the listener to be used when a dismiss event occurs
swipe.setListener(
new SwipeDismissBehavior.OnDismissListener() {
@Override public void onDismiss(View view) {
//......
}
@Override
public void onDragStateChanged(int state) {
//......
}
});
//Attach the SwipeDismissBehavior to a view
LayoutParams coordinatorParams =
(LayoutParams) mView.getLayoutParams();
coordinatorParams.setBehavior(swipe);
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](http://stackoverflow.com/documentation/android/5714/coordinatorlayout-and-behaviors/20239/creating-a-simple-behavior#t=201608310823294520346):
Override 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`. This method is called every time a change occurs to the layout:
@OverridepublicbooleanlayoutDependsOn(CoordinatorLayout parent,ImageView child,View dependency){// Returns true to add a dependency.return dependency instanceofToolbar;}
Whenever the method [`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:
@OverridepublicbooleanonDependentViewChanged(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);}
By specifying Behaviors(opens new window) for child views of a CoordinatorLayout you can provide many different interactions within a single parent and those views can also interact with one another. View classes can specify a default behavior when used as a child of a CoordinatorLayout using the DefaultBehavior annotation.