Recyclerview scrollToPosition does not work

半世苍凉 提交于 2019-12-12 06:30:48

问题


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.

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);

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); 

Thank you so much for reading this.


回答1:


Use

layoutManager.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




回答2:


Try with this

layoutManager.scrollToPosition(index);


来源:https://stackoverflow.com/questions/41357303/recyclerview-scrolltoposition-does-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!