Skip to content

Instantly share code, notes, and snippets.

@f2face
Last active February 29, 2020 05:38
Show Gist options
  • Save f2face/0f271cefceb115cb9b618b47fc01b127 to your computer and use it in GitHub Desktop.
Save f2face/0f271cefceb115cb9b618b47fc01b127 to your computer and use it in GitHub Desktop.
Imagine you're implementing a horizontal RecyclerView and you want the items inside it to have equal space.
// This snippet should be in your adapter class
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
// Set grid items spacing
if (holder.container.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) holder.container.getLayoutParams();
int marginStart = 16; // 16dp
p.setMarginStart((int) (marginStart * holder.container.getResources().getDisplayMetrics().density));
// Last position
if (position == getItemCount()-1) {
int marginEnd = 16; // 16dp
p.setMarginEnd((int) (marginEnd * holder.container.getResources().getDisplayMetrics().density));
}
// Other position
else {
p.setMarginEnd(0); // No margin
}
holder.container.requestLayout();
}
}
static class MyViewHolder extends RecyclerView.ViewHolder {
View container;
MyViewHolder(View v) {
super(v);
container = v;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment