Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rodrigoborgesdeoliveira/a37b1534969fe4e9ada0bb440b8f4b4b to your computer and use it in GitHub Desktop.
Save rodrigoborgesdeoliveira/a37b1534969fe4e9ada0bb440b8f4b4b to your computer and use it in GitHub Desktop.
This shows or hides a floating action button when the recycler view is scrolled. It also adds a blank space after the list's last item to make sure that if the list is too short to be scrolled, it'll still be scrollable to hide the floating action button that is sitting on top of the last item.
// This code is inside the recycler view adapter class
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
if (position + 1 == getItemCount()) {
// It is the last item of the list
// Set bottom margin to 72dp
setBottomMargin(holder.itemView, (int) (72 * Resources.getSystem().getDisplayMetrics().density));
} else {
// Reset bottom margin back to zero
setBottomMargin(holder.itemView, 0);
}
}
/**
* Sets a margin to the bottom of the view.
*
* @param view The view to add the margin to.
* @param bottomMargin The bottom margin to be added to the view.
*/
private static void setBottomMargin(View view, int bottomMargin) {
if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
params.setMargins(params.leftMargin, params.topMargin, params.rightMargin, bottomMargin);
view.requestLayout();
}
}
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (dy < 0) {
// Scrolled up, show floating action button
fab.show();
} else if (dy > 0) {
// Scrolled down, hide floating action button
fab.hide();
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment