如何为最后一个元素向RecyclerView添加边距



I有几个屏幕使用RecyclerView,在RecyclerView的顶部也有一个小的Fragment。当显示Fragment时,我想确保我可以滚动到RecyclerView的底部。Fragment并不总是显示。如果我在RecyclerView上使用页边空白,我需要在显示Fragment时动态删除和添加它们。我可以在列表中的最后一项上添加边距,但这也很复杂,如果我稍后加载更多内容(即分页),我将不得不再次去掉这些边距。

如何在视图中动态添加或删除页边距?还有什么其他选择可以解决这个问题?

因此,如果您想在RecyclerView的底部添加一些填充,可以将paddingBottomclipToPadding设置为false。这里有一个的例子

<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" />

您应该使用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 */;
        }
    }
}

我在kotlin中使用它来给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 ...
}

Item decorator是我的最佳解决方案

使用此kotlin溶液

    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
        }
    }
}

然后像这个一样使用它

recyclerview.addItemDecoration(RecyclerItemDecoration())

最新更新