简体   繁体   English

RecyclerView:使用自定义 ItemDecoration 为最后一个项目添加底部间距不适用于 DividerItemDecoration 和 ItemTouchHelper

[英]RecyclerView: Adding bottom spacing for last item with a custom ItemDecoration doesn't work well with DividerItemDecoration and ItemTouchHelper

I am adding a space below the last item in the RecyclerView using this popular and efficient solution:我使用这种流行且高效的解决方案在 RecyclerView 的最后一项下方添加了一个空格:

class ListMarginDecorator(
        private val left: Int = 0,
        private val top: Int = 0,
        private val right: Int = 0,
        private val bottom: Int = 0,
) : RecyclerView.ItemDecoration() {
    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
        super.getItemOffsets(outRect, view, parent, state)
        val position = parent.getChildAdapterPosition(view)

        outRect.left = left
        outRect.top = if (position == 0) top else 0
        outRect.right = right
        outRect.bottom = if (position == state.itemCount - 1) bottom else 0
    }
}

I also add item dividers using DividerItemDecoration , and enable drag-to-reorder by implementing ItemTouchHelper .我还使用DividerItemDecoration添加项目分隔符,并通过实现ItemTouchHelper启用拖动重新排序。

Here is how I use these ItemDecorators in the fragment class:以下是我在片段 class 中使用这些 ItemDecorators 的方法:

binding.recyclerView.addItemDecoration(
    DividerItemDecoration(
            binding.rvCurrencies.context,
            DividerItemDecoration.VERTICAL
    )
)

binding.recyclerView.addItemDecoration(
    ListMarginDecorator(
        bottom = resources.getDimensionPixelSize(R.dimen.list_last_item_bottom_margin) // = 88dp
    )
)

I see two issues with this approach to space under the last item though.不过,我在最后一项下看到了这种空间处理方法的两个问题。

The first is that ListMarginDecorator seems to be applying padding, not margin, so the bottom divider line for the last item in the list is drawn below the spacing that is applied to that last item.首先是 ListMarginDecorator 似乎正在应用填充,而不是边距,因此列表中最后一项的底部分隔线绘制在应用于最后一项的间距下方

分频器问题

The second issue is that I can no longer drag an item in the list to the bottom-most position.第二个问题是我不能再将列表中的项目拖到最底部的 position。

拖到底部问题

When I comment out the line adding the ListMarginDecorator though, both of these work as expected:当我注释掉添加 ListMarginDecorator 的行时,这两个都按预期工作:

作品

Is there any other way to efficiently add a space under the last item, without running into these issues?有没有其他方法可以有效地在最后一项下添加空格,而不会遇到这些问题?

If you want space after the last item, why don't just use如果你想要最后一项之后的空间,为什么不直接使用

rvCurrencies.setPadding(0, 0, 0, 100)
rvCurrencies.clipToPadding = false

or in XML或在 XML

android:paddingBottom="100dp"
android:clipToPadding="false"

in this way, your all two problems will be sorted out.这样,你的这两个问题就迎刃而解了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM