Java – RecyclerView is clicked programmatically

RecyclerView is clicked programmatically… here is a solution to the problem.

RecyclerView is clicked programmatically

I’m trying to programmatically click on a project that recyclerView. I’m using:

recyclerView.findViewHolderForAdapterPosition(index).itemView.performClick();

This is very effective when the index is a visible item. If the item is not visible (for example, at the last position of the recyclerview), an exception is thrown.

What can I do?

Solution

I just had a similar issue with you. I’ve solved it! Here’s what I did.

xxx.mRecyclerView.postDelayed(new Runnable() {
            @Override
            public void run() {
                xx.mRecyclerView.scrollToPosition(position);
            }
        },300);

xxx.mRecyclerView.postDelayed(new Runnable() {
            @Override
            public void run() {
                xxx.mRecyclerView.findViewHolderForAdapterPosition(position).itemView.performClick();
                }
            },400);
        }

You can scroll to a specific item and perform a click.
Because Doc said

If the item at the given position is not laid out, it will not create a new one.

But I know the adapter has data, so scroll to it first and findViewHolderForAdapterPosition won’t be empty.

Another point, I don’t know how you use RecyclerView. In my app, I’m using it in a fragment and I don’t know why we’re delaying it scrolling and performing clicks. (Maybe it’s the reason for the circle of life, right?) But it worked.

Related Problems and Solutions