RecyclerView Sticky Footer与DividerItemDecoration

时间:2017-03-03 05:05:20

标签: android android-recyclerview footer

之前可能已经提出过这个问题,但我无法找到解决我面临的确切问题的方法。我需要在我的RecyclerView中添加一个页脚,以便页脚与其余项目一起滚动。我从这篇文章中获取灵感来创建一个FooterDecoration,它将布局添加到列表的末尾。 https://stackoverflow.com/a/33458367

除了FooterDecoration之外,我还添加了DividerItemDecoration。

这种方法的问题是页脚在最后一个分隔项之前而不是之后添加。如何添加页脚以便在最后一个项目分隔符后添加?

此代码位于Kotlin。

class FooterDecoration(
    val context: Context,
    val parent: RecyclerView,
    var layout: View
) : RecyclerView.ItemDecoration() {
  init {
    layout.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.AT_MOST),
        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
  }

  override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
    super.onDraw(c, parent, state)     
    layout.layout(parent.left, 0, parent.right, layout.measuredHeight)

    for (i in 0..parent.childCount - 1) {
      val view = parent.getChildAt(i)
      if (parent.getChildAdapterPosition(view) == parent.adapter.itemCount.minus(1)) {
        c.save()
        val top = view.bottom
        c.translate(0f, top.toFloat())
        layout.draw(c)
        c.restore()
        break
      }
    }
  }

  override fun getItemOffsets(
      outRect: Rect,
      view: View,
      parent: RecyclerView,
      state: RecyclerView.State
  ) {
    if (parent.getChildAdapterPosition(view) == parent.adapter.itemCount.minus(1)) {
      outRect.set(0, 0, 0, layout.measuredHeight)
    } else {
      outRect.setEmpty()
    }
  }
}

知道我之前添加DividerItemDecoration可能会有所帮助 FooterDecoration。

我错过了什么?谢谢你的帮助。

适配器代码:

class PlanCategoryAdapter(
    val planNodes: List<Nodes>,
    val context: Context
) : RecyclerView.Adapter<CategoryViewHolder>() {

  override fun getItemCount(): Int {
    return planNodes.size
  }

  override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoryViewHolder {
    val view = LayoutInflater.from(context).inflate(R.layout.view_category_item, parent, false)
    return CategoryViewHolder(view)
  }

  override fun onBindViewHolder(holder: CategoryViewHolder, position: Int) {
    val searchNode = planNodes[position]
    holder.bind(searchNode)
  }
}

class CategoryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

  val tvTitle: TextView by bindView(R.id.tvTitle)

  fun bind(planNode: Node) {
    tvTitle.text = planNode.displayName
  }
}

0 个答案:

没有答案