Reputation: 38789
I several screens that use RecyclerView
and also has a small Fragment
that is on top of the RecyclerView
. When that Fragment
is displayed I'd like to make sure I can scroll to the bottom of the RecyclerView
. The Fragment
isn't always displayed. If I used margins on the RecyclerView
I'd need to dynamically remove and add them when the Fragment
is displayed. I could add margins onto the last item in the list, but that is also complicated and if I load more things later (ie pagination) I'd have to strip off those margins again.
How would I dynamically add or remove margins to the view? What are some other options to solve this?
Upvotes: 31
Views: 15029
Reputation: 41
Item decorator is the best solution for me
Use this kotlin solution
class RecyclerItemDecoration: RecyclerView.ItemDecoration() {
override fun getItemOffsets(
outRect: Rect,
view: View,
parent: RecyclerView,
state: RecyclerView.State
) {
if (parent.getChildAdapterPosition(view) == parent.adapter!!.itemCount - 1) {
outRect.bottom = 80
}
}
}
Then use it like this
recyclerview.addItemDecoration(RecyclerItemDecoration())
Upvotes: 1
Reputation: 13565
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 ...
}
Upvotes: 5
Reputation: 29280
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 */;
}
}
}
Upvotes: 20
Reputation: 24211
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" />
Upvotes: 96