Sobes.tech
Middle

Šta je ItemDecoration i kako se koristi u Androidu?

sobes.tech АИ

Одговор од АИ

ItemDecoration се користи за цртање украса око појединачних елемената RecyclerView или изнад целокупне површине RecyclerView.

Основне функције:

  • Цртање раздвајача између елемената (линије, размаке).
  • Цртање позадина или оквира за елементе.
  • Додавање размакa (padding) око елемената без промене распореда самог елемента.

Како користити:

  1. Направите класу која наследи RecyclerView.ItemDecoration.
  2. Препишите потребне методе:
    • onDraw(Canvas c, RecyclerView parent, RecyclerView.State state): за цртање украса испод елемената.
    • onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state): за цртање украса над елементима.
    • getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state): за додавање размакa до граница елемента.
  3. Креирајте инстанцу класе ItemDecoration.
  4. Додајте је у RecyclerView помоћу addItemDecoration(ItemDecoration decoration).

Пример за коришћење getItemOffsets за додавање размакa:

class SpaceItemDecoration(private val spaceHeight: Int) : RecyclerView.ItemDecoration() {
    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
        with(outRect) {
            if (parent.getChildAdapterPosition(view) == 0) {
                top = spaceHeight // Размак изнад само за први елемент
            }
            left =  spaceHeight
            right = spaceHeight
            bottom = spaceHeight
        }
    }
}

// У коду где се конфигурише RecyclerView:
// val recyclerView = findViewById<RecyclerView>(R.id.my_recycler_view)
// recyclerView.addItemDecoration(SpaceItemDecoration(resources.getDimensionPixelSize(R.dimen.item_space)))

Пример за коришћење onDraw за цртање раздвајача:

class DividerItemDecoration(private val dividerHeight: Int, private val dividerColor: Int) : RecyclerView.ItemDecoration() {
    private val paint = Paint().apply {
        color = dividerColor
        style = Paint.Style.FILL
    }

    override fun onDraw(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        val left = parent.paddingLeft
        val right = parent.width - parent.paddingRight

        for (i in 0 until parent.childCount - 1) { // до предпоследњег елемента
            val child = parent.getChildAt(i)
            val top = child.bottom
            val bottom = top + dividerHeight
            canvas.drawRect(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat(), paint)
        }
    }

    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
        // Додај место за раздвајач ако није последњи елемент
        if (parent.getChildAdapterPosition(view) != parent.adapter?.itemCount?.minus(1)) {
            outRect.bottom = dividerHeight
        }
    }
}

// У коду где се конфигурише RecyclerView:
// val recyclerView = findViewById<RecyclerView>(R.id.my_recycler_view)
// recyclerView.addItemDecoration(DividerItemDecoration(resources.getDimensionPixelSize(R.dimen.divider_height), ContextCompat.getColor(this, R.color.divider_color)))

Важно је разумети да ItemDecoration не мења величине или распоред самих елемената, већ утиче само на њихово цртање и размаке око њих.