Recyclerview разделитель с пользовательским заполнением

1

Как добавить пользовательские отступы в горизонтальный разделитель, используемый в RecyclerView?

Пока это мое решение, но отступы полностью игнорируются:

import android.content.Context
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.RecyclerView
import android.util.TypedValue


class CustomDecoration(val context: Context?, orientation: Int, private val padding: Float) : DividerItemDecoration(context, orientation) {

    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
        val position = parent.getChildAdapterPosition(view)


        outRect.right = dpToPx(padding)
        outRect.left = dpToPx(padding)

        // hide the divider for the last child
        if (position == parent.adapter!!.itemCount - 1) {
            outRect.setEmpty()
        } else {
            super.getItemOffsets(outRect, view, parent, state)
        }
    }

    fun dpToPx(dp: Float): Int{
        val metrics = context?.resources?.displayMetrics
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, metrics).toInt()
    }
}
Теги:
android-recyclerview
android-layout

1 ответ

1
Лучший ответ

Это потому, что вы вызываете super.getItemOffsets(outRect, view, parent, state)

если вы посмотрите на этот метод, вы заметите, что он сбрасывает все значения

  public void getItemOffsets(@NonNull Rect outRect, int itemPosition, @NonNull RecyclerView parent) {
        outRect.set(0, 0, 0, 0);
    }

так что настройте свой код так, чтобы он работал

override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
                super.getItemOffsets(outRect, view, parent, state)

        val position = parent.getChildAdapterPosition(view)


        outRect.right = dpToPx(padding)
        outRect.left = dpToPx(padding)

        // hide the divider for the last child
        if (position == parent.adapter!!.itemCount - 1) {
            outRect.setEmpty()
        }
    }

    fun dpToPx(dp: Float): Int{
        val metrics = context?.resources?.displayMetrics
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, metrics).toInt()
    }

Ещё вопросы

Сообщество Overcoder
Наверх
Меню