Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i move to next object in recyclerview on button click

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);
like image 692
J DEO Avatar asked Oct 28 '25 14:10

J DEO


1 Answers

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;
}
like image 183
jantursky Avatar answered Oct 31 '25 03:10

jantursky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!