RecyclerView滑动到指定Item并置顶

RecyclerView滑动到指定Item并置顶

0x01 TopLinearSmoothScroller

1
2
3
4
5
6
7
8
9
10
11
12
import android.content.Context
import androidx.recyclerview.widget.LinearSmoothScroller

class TopLinearSmoothScroller(context: Context?) : LinearSmoothScroller(context) {
public override fun getVerticalSnapPreference(): Int {
return SNAP_TO_START
}

override fun getHorizontalSnapPreference(): Int {
return SNAP_TO_START
}
}

0x02 TopScrollLinearLayoutManager

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import android.content.Context
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

class TopScrollLinearLayoutManager(context: Context?, orientation: Int, reverseLayout: Boolean) :
LinearLayoutManager(context, orientation, reverseLayout) {

override fun smoothScrollToPosition(
recyclerView: RecyclerView?,
state: RecyclerView.State?,
position: Int
) {
val linearSmoothScroller = TopLinearSmoothScroller(recyclerView?.context)
linearSmoothScroller.targetPosition = position
startSmoothScroll(linearSmoothScroller)
}
}

0x03 RecyclerView中使用

设置recyclerView的layoutManager为自定义的TopScrollLinearLayoutManager,然后直接调用 smoothScrollToPosition() 方法就可以滚动到指定的位置并且置顶了。

1
2
3
4
5
6
7
recyclerView.layoutManager = TopScrollLinearLayoutManager(
this,
LinearLayoutManager.HORIZONTAL,
false
)
// ...
recyclerView.smoothScrollToPosition(1)
作者

Dench

发布于

2023-03-24

更新于

2023-03-24

许可协议

CC BY-NC-SA 4.0

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×