ItemDecoration ViewType에 따라 다른 divider 주기

나고수·2022년 3월 19일
0

1일1공부

목록 보기
23/68
class Decoration(
    context: Context,
    resId: Int,
    val paddingLeft: Int,
    val paddingRight: Int
) : RecyclerView.ItemDecoration() {
    private var mDivider: Drawable? = null

    init {
        mDivider = ContextCompat.getDrawable(context, resId)
    }

    override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        val left = parent.paddingLeft + paddingLeft
        val right = parent.width - parent.paddingRight - paddingRight
        val childCount = parent.childCount

        for (i in 0 until childCount) {
            val child = parent.getChildAt(i)
            val position = parent.getChildAdapterPosition(child)
            val viewType = parent.adapter?.getItemViewType(position) //뷰타입 체크
            
			//뷰타입이 특정 뷰 타입일 때만 데코레이션 넣기 이런게 가능함.
            if (viewType == ViewType.myType.type) {
                val params = child.layoutParams as RecyclerView.LayoutParams
                val top = child.bottom + params.bottomMargin
                val bottom = top + (mDivider?.intrinsicHeight ?: 0)
                mDivider?.let {
                    it.setBounds(left, top, right, bottom)
                    it.draw(c)
                }
            }
        }
    }

}

enum class ViewType(val type: Int) {
    myType(0)
}
profile
되고싶다

0개의 댓글