cry*_*yyy 26 android scroll android-recyclerview
这RecyclerView.scrollToPosition()是非常奇怪的.例如,假设一个RecyclerView名字"rv".
如果现在项目10在当前RecyclerView,呼叫rv.scrollToPosition(10),RecyclerView则将项目10滚动到底部.
如果现在项目10在当前RecyclerView,呼叫rv.scrollToPosition(10),将不会有任何滚动,将不会做任何事情.
如果现在项目10位于当前的顶部,则RecyclerView调用rv.scrollToPosition(10),RecyclerView将项目10滚动到顶部.
但我需要的是,每当我调用它时,RecyclerView就会像案例3一样将所谓的位置滚动到当前视图的顶部.如何做到这一点?
yug*_*oid 45
如果我理解了这个问题,你想滚动到一个特定的位置,但该位置是适配器的位置,而不是RecyclerView项目的位置.
你只能通过这个来实现这一目标LayoutManager.
做类似的事情:
rv.getLayoutManager().scrollToPosition(youPositionInTheAdapter).
Run Code Online (Sandbox Code Playgroud)
Rit*_*esh 14
以下链接可能会解决您的问题:
只需创建一个具有首选项SNAP_TO_START的SmoothScroller:
RecyclerView.SmoothScroller smoothScroller = new
LinearSmoothScroller(context) {
@Override protected int getVerticalSnapPreference() {
return LinearSmoothScroller.SNAP_TO_START;
}
};
Run Code Online (Sandbox Code Playgroud)
现在,您可以设置要滚动到的位置:
smoothScroller.setTargetPosition(position);
Run Code Online (Sandbox Code Playgroud)
并将SmoothScroller传递给LayoutManager:
layoutManager.startSmoothScroll(smoothScroller);
Run Code Online (Sandbox Code Playgroud)
这是 Kotlin 代码片段,但您可以正确地按位置滚动到项目。重点是声明布局管理器的成员变量并使用其方法进行滚动。
lateinit var layoutManager: LinearLayoutManager
fun setupView() {
...
layoutManager = LinearLayoutManager(applicationContext)
mainRecyclerView.layoutManager = layoutManager
...
}
fun moveToPosition(position: Int) {
layoutManager.scrollToPositionWithOffset(position, 0)
}
Run Code Online (Sandbox Code Playgroud)
如果您想滚动到特定位置并且该位置是适配器的位置,那么您可以使用StaggeredGridLayoutManager scrollToPosition
StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
staggeredGridLayoutManager.scrollToPosition(10);
recyclerView.setLayoutManager(staggeredGridLayoutManager);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
66219 次 |
| 最近记录: |