Last active
May 23, 2023 12:42
-
-
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 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
// 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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment