具有自定义填充的Recyclerview分隔符

时间:2019-03-26 12:38:05

标签: android android-layout android-recyclerview

如何向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()
    }
}

1 个答案:

答案 0 :(得分: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()
    }