How to add margins to a RecyclerView for the last element?
I use this in kotlin for give margin to last index of RecyclerView
override fun onBindViewHolder(holder: RecyclerView.ViewHolder(view), position: Int) {
if (position == itemsList.lastIndex){
val params = holder.itemView.layoutParams as FrameLayout.LayoutParams
params.bottomMargin = 100
holder.itemView.layoutParams = params
}else{
val params = holder.itemView.layoutParams as RecyclerView.LayoutParams
params.bottomMargin = 0
holder.itemView.layoutParams = params
}
//other codes ...
}
You should use the Item Decorator.
public class MyItemDecoration extends RecyclerView.ItemDecoration {
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
// only for the last one
if (parent.getChildAdapterPosition(view) == parent.getAdapter().getItemCount() - 1) {
outRect.top = /* set your margin here */;
}
}
}
So if you want to add some padding at the bottom of your RecyclerView
you can set the paddingBottom
and then clipToPadding
to false. Here's an example
<android.support.v7.widget.RecyclerView
android:id="@+id/my_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:paddingBottom="100dp" />