Skip to content

Instantly share code, notes, and snippets.

@jmarkovic
Created February 24, 2016 22:12
Show Gist options
  • Save jmarkovic/2e2c366e0b45abca752d to your computer and use it in GitHub Desktop.
Save jmarkovic/2e2c366e0b45abca752d to your computer and use it in GitHub Desktop.
A CoordinatorLayout Behavior for any scroll view, that mimics that slingy feeling and behavior that scrolling containers do on iOS. This is just a proof of concept. Fling currently does not work.
public class SlingyBehavior<V extends View> extends CoordinatorLayout.Behavior<V> implements ViewPropertyAnimatorUpdateListener {
private int moveX = 0;
private int moveY = 0;
public SlingyBehavior() {
super();
}
public SlingyBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, V child, View directTargetChild, View target,
int nestedScrollAxes) {
ViewCompat.animate(child).setUpdateListener(null).cancel();
return true;
}
@Override
public void onStopNestedScroll(CoordinatorLayout coordinatorLayout, V child, View target) {
ViewCompat.animate(child).translationX(0).translationY(0).setUpdateListener(this).start();
}
@Override
public void onNestedScroll(CoordinatorLayout coordinatorLayout, V child, View target, int dxConsumed, int dyConsumed, int dxUnconsumed,
int dyUnconsumed) {
if (dxUnconsumed != 0) {
moveX += dxUnconsumed;
ViewCompat.setTranslationX(child, moveX);
}
if (dyUnconsumed != 0) {
moveY += dyUnconsumed;
ViewCompat.setTranslationY(child, moveY);
}
}
@Override
public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, V child, View target, int dx, int dy, int[] consumed) {
if (moveX != 0) {
moveX += dx;
if (moveX != 0) {
consumed[0] = dx;
}
ViewCompat.setTranslationX(child, - moveX);
}
if (moveY != 0) {
moveY += dy;
if (moveY != 0) {
consumed[1] = dy;
}
ViewCompat.setTranslationY(child, - moveY);
}
}
@Override
public void onAnimationUpdate(View view) {
moveX = (int) ViewCompat.getTranslationX(view);
moveY = (int) ViewCompat.getTranslationY(view);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment