Created
December 27, 2018 07:56
-
-
Save haroldadmin/1ad316e87f6be98af282c1039647a2c3 to your computer and use it in GitHub Desktop.
AppBarLayout Behaviour Extension which shows/hides FAB on content scroll
This file contains 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 class ScrollAwareFABBehavior | |
extends AppBarLayout.ScrollingViewBehavior { | |
public ScrollAwareFABBehavior(Context context, AttributeSet attrs) { | |
super(context, attrs); | |
} | |
@Override | |
public boolean layoutDependsOn(CoordinatorLayout parent, | |
View child, View dependency) { | |
return super.layoutDependsOn(parent, child, dependency) || | |
dependency instanceof FloatingActionButton; | |
} | |
@Override | |
public boolean onStartNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull View child, @NonNull View directTargetChild, @NonNull View target, int axes, int type) { | |
return axes == ViewCompat.SCROLL_AXIS_VERTICAL || super.onStartNestedScroll | |
(coordinatorLayout, child, | |
directTargetChild, | |
target, axes, type); | |
} | |
@Override | |
public void onNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull View child, @NonNull View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int type) { | |
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type); | |
if (dyConsumed > 0) { | |
// User scrolled down -> hide the FAB | |
List<View> dependencies = coordinatorLayout.getDependencies(child); | |
for (View view : dependencies) { | |
if (view instanceof FloatingActionButton) { | |
((FloatingActionButton) view).hide(); | |
} | |
} | |
} else if (dyConsumed < 0) { | |
// User scrolled up -> show the FAB | |
List<View> dependencies = coordinatorLayout.getDependencies(child); | |
for (View view : dependencies) { | |
if (view instanceof FloatingActionButton) { | |
((FloatingActionButton) view).show(); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment