helloimyourmind helloimyourmind - 5 months ago 113
Android Question

RecyclerView programmatically click

I'm trying to programmatically click on an item of a recyclerView. I'm using:

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


This perfectly works when the index is of a visible item. If the item is not visible (at the last position of the recyclerview, for istance), an Exception is thrown.

What can I do?

Answer

You could call onClick directly, assuming that view manages its own click listener.

View view = recyclerView.findViewHolderForAdapterPosition(index).itemView;
view.onClick(view);

If the click listener is located somewhere else, you just need to get a reference to the object with the onClick method and call it with the correct view as a parameter.