Skip to content

Instantly share code, notes, and snippets.

@haroldadmin
Created December 27, 2018 07:56
Show Gist options
  • Save haroldadmin/1ad316e87f6be98af282c1039647a2c3 to your computer and use it in GitHub Desktop.
Save haroldadmin/1ad316e87f6be98af282c1039647a2c3 to your computer and use it in GitHub Desktop.
AppBarLayout Behaviour Extension which shows/hides FAB on content scroll
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