How to scroll horizontal RecyclerView programmatically?

匆匆过客 提交于 2019-11-27 01:38:04

问题


I have a horizontal RecyclerView and two button (Next,Previous) as shown in the image below.

so i need to move to the next item or position by use these buttons , i know about method called scrollTo but i don't know how does it work


回答1:


Simply if found the answer:

case R.id.next:
    mRecyclerView.getLayoutManager().scrollToPosition(linearLayoutManager.findLastVisibleItemPosition() + 1);
    break;
case R.id.pre:
    mRecyclerView.getLayoutManager().scrollToPosition(linearLayoutManager.findFirstVisibleItemPosition() - 1);
    break;



回答2:


RecyclerViews have a methods which they expose for scrolling to a certain position:

Snap scroll to a given position:

mRecyclerView.scrollToPosition(int position)

Smooth scroll to a given position:

mRecyclerView.smoothScrollToPosition(int position)

For these methods to work, the LayoutManager of the RecyclerView needs to have implemented these methods, and LinearLayoutManager does implement these in a basic manner, so you should be good to go.




回答3:


case R.id.next:
    mRecyclerView.getLayoutManager().scrollToPosition(linearLayoutManager.findLastVisibleItemPosition() + 1);
    break;

case R.id.pre:
    mRecyclerView.getLayoutManager().scrollToPosition(linearLayoutManager.findFirstVisibleItemPosition() - 1);
    break;



回答4:


int mFirst=0, mLast=0;

recyclerview.setOnScrollListener(new RecyclerView.OnScrollListener() {
    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);
    }
    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        LinearLayoutManager llm = (LinearLayoutManager) recyclerview.getLayoutManager();
        mLast = llm.findLastCompletelyVisibleItemPosition();
        mFirst = llm.findFirstCompletelyVisibleItemPosition();
    }
});

imgRight.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        LinearLayoutManager llm = (LinearLayoutManager) recyclerview.getLayoutManager();
        llm.scrollToPositionWithOffset(mLast + 1, List.length());
    }
});

imgLeft.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        LinearLayoutManager llm = (LinearLayoutManager) recyclerview.getLayoutManager();
        llm.scrollToPositionWithOffset(mFirst - 1, List.length());
    }
});


来源:https://stackoverflow.com/questions/32035427/how-to-scroll-horizontal-recyclerview-programmatically

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