Recyclerview scrollToPosition不起作用 [英] Recyclerview scrollToPosition does not work
问题描述
我已经尝试了所有问题,从答案到关于stackoverflow的问题,但我仍然无法弄清楚.在我的一个recyclerview视图中,单击一个按钮后便能够滚动到所需位置.在另一个recyclerview上(它的构建方式与第一个类似),我无法滚动到所需位置.
I have tried everything from the answers to the questions on stackoverflow, but I still could not figure this out. In one of my recyclerview, I was able to scroll to the desired position after a click of a button. On a different recyclerview (it was built similar to the first one), I was not able to scroll to the desired position.
这是有效的recyclerview的代码:
This is the code for the recyclerview that worked:
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
Button button = (Button) view.findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
newFeedRecyclerView.smoothScrollToPosition(2);
}
});
FeedRecyclerAdapter adapter = new FeedRecyclerAdapter(view.getContext(), allRows);
newFeedRecyclerView.setHasFixedSize(true);
newFeedRecyclerView.setLayoutManager(layoutManager);
newFeedRecyclerView.addItemDecoration(new VerticalSpaceItemDecorator(30));
newFeedRecyclerView.setAdapter(adapter);
这是针对无效的recyclerview的:
And this is for the recyclerview that did not work:
allImageRecycleView.addItemDecoration(new VerticalSpaceItemDecorator(30));
allImageRecycleView.setNestedScrollingEnabled(false);
allImageRecycleView.setHasFixedSize(true);
LinearLayoutManager layoutManager = new >LinearLayoutManagerWithSmoothScroller(getContext());
Button button = (Button)view.findViewById(R.id.button3);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
allImageRecycleView.smoothScrollToPosition(2);
}
});
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
allImageRecycleView.setLayoutManager(layoutManager);
allImageRecycleView.setAdapter(allImageRecyclerAdapter);
非常感谢您阅读本文.
推荐答案
使用
layoutManager.scrollToPositionWithOffset(int position, int offset)
scrollToPositionWithOffset(int position,int offset)滚动到指定的适配器位置,相对于已解决的布局具有给定的偏移量开始.
scrollToPositionWithOffset(int position, int offset) Scroll to the specified adapter position with the given offset from resolved layout start.
src: https://developer.android.com/reference/android/support/v7/widget/LinearLayoutManager.html
这篇关于Recyclerview scrollToPosition不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!