防止 ItemDecorator 将分隔符添加到我的视图类型

Prevent ItemDecorator to add dividers to my viewtypes

我用 ConcatAdapter 制作了一个 recyclerview,想法是这些适配器中的每一个都有 2 种视图类型,一种用于 header,一种用于项目,现在,当应用带有 itemDecorator 的分隔符时这些适配器应用于每个视图类型,但我不想将装饰器应用于所有视图类型,而是在内容视图类型

之后
 //Merge all together
        val concatAdapter = ConcatAdapter(
            firstConcatAdapter,
            secondConcatAdapter,
            thirdConcatAdapter
        )

        val dividerItemDecorationInstance =
            DividerItemDecoration(requireContext(), LinearLayoutManager.VERTICAL)
        test_rv.addItemDecoration(dividerItemDecorationInstance)
        dividerItemDecorationInstance.setDrawable(
            ContextCompat.getDrawable(
                requireContext(),
                R.drawable.recycler_home_divider
            )!!
        )
        test_rv.layoutManager = LinearLayoutManager(requireContext())
        test_rv.adapter = concatAdapter

所以这里 test_rv 是一个 recyclerview,我在这个 recyclerview 中膨胀不同的适配器,我在其中显示 UI 的不同自定义部分,每个适配器,firstConcatAdapter 等等都有 2 种视图类型,它有一个 header 然后是项目,但我的输出是这个

所以这里发生的事情是分隔线也应用于 header 视图类型,我不希望它显示在那里,我只需要在所有视图都用其视图类型膨胀后的分隔线

您可以扩展 ItemDecoration 并使您的逻辑显示与项目类型相关的分隔符,假设您的项目类型为 (header项目)

import android.graphics.Canvas
import android.graphics.Paint
import androidx.recyclerview.widget.RecyclerView


class HorizontalItemDecoration(
color: Int,
private val heightInPixels: Int) : RecyclerView.ItemDecoration() {

private val paint = Paint()

 init {
  paint.color = color
  paint.isAntiAlias = true
 }

override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
super.onDraw(c, parent, state)

val left = parent.paddingLeft
val right = parent.width - parent.paddingRight

val childCount = parent.childCount
for (i in 0 until childCount) {
  val child = parent.getChildAt(i)

  val params = child.layoutParams as RecyclerView.LayoutParams

  val top = child.bottom + params.bottomMargin
  val bottom = top + heightInPixels
  val adapterPosition = parent.getChildAdapterPosition(child)
  val viewType= parent.adapter.getItemViewType(adapterPosition )
  if (viewType == RowType.ITEM.ordinal) { // here you make check before drawing the divider where row type determine if this item is header or normal item
    c.drawRect(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat(), paint)
   }
  }
 }
}

行类型枚举

enum class RowType {
ITEM,
HEADER;
}

使用 ItemDecoration

val dividerHeightInPixels = resources.getDimensionPixelSize(R.dimen.1sdp)
val dividerItemDecoration = HorizontalItemDecoration(ContextCompat.getColor(requireContext(), R.color.divider_color), dividerHeightInPixels)
recyclerView.addItemDecoration(dividerItemDecoration)