问题
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