'Calculate views distance from top inside a recyclerView
I have recently been trying to implement a calendar day view (see picture) with items laying on top of a recycler view
Example of part of the calendar view
Currently I calculate the offset the item needs to have from the top of the recycler view with this bit of code
val dpPerMinute = 24f / 15f
val viewOffset = 12f
initialOffset = (startTime * dpPerMinute + viewOffset + 4f).dpToPx().toInt()
The background item height is 24dp and is equal to 15 minutes, viewOffset is just to offset the view to the center of the itemHeight and the 4 comes from padding
Whenever I scroll in the view I update the position of the item with this
val pos = -offset + initialOffset
view?.translationY = pos.toFloat()
Offset is the recycler views current scroll Y and initialOffset is calculated above
This works great on my Samsung, everything lines up perfectly. But then comes the problem, I tested it on another work phone (as we do, a OnePlus Nord) and now everything isn't lining up right. The offset becomes more off the further down it is.
Could this be a problem with converting dp to pixels on different phones? Has anyone else encountered the same problem as me with other phones and if that is the case how did you solve it?
The function converting dp to px looks like following:
@JvmOverloads @Dimension(unit = Dimension.PX) fun Number.dpToPx(
metrics: DisplayMetrics = Resources.getSystem().displayMetrics
): Float {
return toFloat() * metrics.density
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
