Reputation: 51
I want to move to next object in recyclerview when button is clicked. I tried using scrollToPosition but i can't figure out how can i get current position of the object. If i put a number in there then it works, but then it only jumps to that position only.
Code i am using to scroll
layoutManager.scrollToPosition(2);
Upvotes: 4
Views: 5875
Reputation: 1130
LinearLayoutManager - methods like findLastCompletelyVisibleItemPosition()
and checking the size of your AdapterItems and scrolling to the next (+1 if findLast < adapter.itemsSize). Very simple logic.
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
Logic for button clicking:
btnClick.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (layoutManager.findLastCompletelyVisibleItemPosition() < (adapter.getItemCount() - 1)) {
layoutManager.scrollToPosition(layoutManager.findLastCompletelyVisibleItemPosition() + 1);
}
}
});
And in your extended Adapter for RecyclerView, you should have something like this:
@Override
public int getItemCount() {
return yourData != null ? yourData.length() : 0;
}
Upvotes: 14
Reputation: 2940
The ViewHolder
has a getAdapterPosition
function returning its position
Upvotes: 0