Last active
April 19, 2017 11:23
-
-
Save farukcankaya/c3ed2e5c03db3772b49378f022ad0ddd to your computer and use it in GitHub Desktop.
Smooth Coordinatorlayout Scrolling, FlingBehavior
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- Add behaviour to AppBarLayout --> | |
<CoordinatorLayout> | |
<AppBarLayout | |
app:layout_behavior="com.farukcankaya.FlingBehavior"> | |
... | |
</AppBarLayout> | |
<CollapsingToolbarLayout> | |
<Toolbar/> | |
... | |
</CollapsingToolbarLayout> | |
<RecyclerView /> | |
... | |
</CoordinatorLayout> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public final class FlingBehavior extends AppBarLayout.Behavior { | |
private static final int TOP_CHILD_FLING_THRESHOLD = 3; | |
private boolean isPositive; | |
public FlingBehavior() { | |
} | |
public FlingBehavior(Context context, AttributeSet attrs) { | |
super(context, attrs); | |
} | |
@Override | |
public boolean onNestedFling(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, float velocityX, float velocityY, boolean consumed) { | |
if (velocityY > 0 && !isPositive || velocityY < 0 && isPositive) { | |
velocityY = velocityY * -1; | |
} | |
View v = target; | |
if (target instanceof SwipeRefreshLayout && velocityY < 0) { | |
v = ((SwipeRefreshLayout) target).getChildAt(0); | |
} | |
if (v instanceof RecyclerView && velocityY < 0) { | |
final RecyclerView recyclerView = (RecyclerView) v; | |
final View firstChild = recyclerView.getChildAt(0); | |
final int childAdapterPosition = recyclerView.getChildAdapterPosition(firstChild); | |
consumed = childAdapterPosition > TOP_CHILD_FLING_THRESHOLD; | |
} | |
return super.onNestedFling(coordinatorLayout, child, target, velocityX, velocityY, consumed); | |
} | |
@Override | |
public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dx, int dy, int[] consumed) { | |
super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed); | |
isPositive = dy > 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment