android-fragments 如何为RecyclerView的最后一个元素添加边距?

ktca8awb  于 2022-11-14  发布在  Android
关注(0)|答案(4)|浏览(208)

我有几个使用RecyclerView的屏幕,并且在RecyclerView的顶部还有一个小的Fragment。当显示Fragment时,我想确保我可以滚动到RecyclerView的底部。Fragment并不总是显示的。如果我在RecyclerView上使用边距,我'我需要在显示Fragment时动态删除和添加它们。我可以在列表的最后一项上添加边距,但这也很复杂,如果我以后加载更多的内容(即分页),我将不得不再次剥离这些边距。
如何动态地添加或删除视图的边距?有哪些其他选项可以解决这个问题?

wljmcqd8

wljmcqd81#

因此,如果你想在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" />
oxosxuxt

oxosxuxt2#

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

ohfgkhjo3#

我在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 ...
}
oaxa6hgo

oaxa6hgo4#

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())

相关问题