我在NestedScrollView中有recyclerView。我想计算recyclerview的速度,但在nestedScrollView中不起作用。
这是用于计算滚动速度的代码,该代码在没有NestedScrollView的情况下有效。我也想使其与NestedScrollView一起使用。
我已将嵌套滚动设置为false,但不起作用
recyclerView.setNestedScrollingEnabled(false)
抽象类ScrollSpeedRecycleViewScrollListener(priv val maxScrollSpeedForAdInjection:Int):RecyclerView.OnScrollListener(){
var currentScrollSpeed: Int = 0
private var previousFirstVisibleItem = 0
private var previousEventTime: Long = 0
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val layoutManager = recyclerView.layoutManager
if (layoutManager is LinearLayoutManager) {
val firstItemPosition = layoutManager.findFirstVisibleItemPosition()
if (previousFirstVisibleItem != firstItemPosition) {
}
}
}
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
when (newState) {
RecyclerView.SCROLL_STATE_IDLE -> {
if (currentScrollSpeed > maxScrollSpeedForAdInjection) {
listNeedsRefresh()
}
currentScrollSpeed = 0
}
}
}
}
速度的概念涉及一定时间范围内的距离。您可以在onScrolled方法中使用dx或dy获取滚动值(距离)。要获取时间,您需要在获取距离值的位置获取一些时间戳,然后使用speed = distance / time
进行计算。但是您还需要计算onScrolled调用之间的差异。因此实际上会以[]
speed = (distance2 - distance1) / (time2 - time1)
您将要遇到的问题是,当用户快速滚动时,该方法将被称为负载,并且每次都需要进行计算,这将对滚动的平滑度产生不利影响。 。
我愿意打赌,有更好的方法可以解决您的问题。