0

I have a custom class to use offsets inside my RecyclerView.

class SpacesItemDecoration(private var space: Int) : RecyclerView.ItemDecoration() {

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

Then I set the offsets in my code like that:

addItemDecoration(SpacesItemDecoration(25))

It works, but it sets the offsets in pixels. How am I supposed to use dp instead of pixels? And why Google preferred using pixels here? It already should be deprecated.

Viktor
  • 566
  • 5
  • 17
  • Thanks for replying, but no. I know that I can convert them, but it's weird. In different phones it will look a little bit different than it should be. – Viktor Sep 07 '20 at 04:39
  • That's because when you use dp you should be using `dimen.xml` resource not an hardcoded integer . And you should be having `dimen.xml` for multiple device types. – ADM Sep 07 '20 at 04:42
  • "In different phones it will look a little bit different than it should be." then you should include what you mean in your question, as the answer you've accepted just describes how to convert them. – Ryan M Sep 08 '20 at 08:53

1 Answers1

2

by this method you should first convert dp to pixels than set

fun Context.dpToPixel(dp: Float): Float {
    return dp * (resources.displayMetrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
}

by this

addItemDecoration(SpacesItemDecoration(dpToPixel(25f)))
Abdur Rehman
  • 1,247
  • 10
  • 13