问题
I have a recycler view and I want to perform click on one of its items.
Here is my code:
mRecyclerView.findViewHolderForAdapterPosition(2).itemView.performClick();
It works fine when the item is visible, but when it is not visible i'm getting a null pointer exception
also i tried scroll to position before perform click but i got same result
Any idea on how to solve this issue?
回答1:
I have solved my problem with this code
mRecyclerView.getLayoutManager().scrollToPosition(17);
search_list.postDelayed(new Runnable() {
@Override
public void run() {
mRecyclerView.findViewHolderForAdapterPosition(17).itemView.performClick();
}
},50);
There is a slight delay for the viewholder to be created. Thus if the item is clicked before viewholder is created an NPE would occur
回答2:
Unfortunately for you, this is working as intended. When a child View is scrolled out of the boundaries of a RecyclerView, the child View is often reused to display another item for another position in the list, hence you will get a null View for the position that is no longer displayed.
What you can do is implement a getItem() on the RecyclerView.Adapter to retrieve the item for that position. Not sure if that satisfies your requirements though.
来源:https://stackoverflow.com/questions/33397683/null-pointer-exception-when-trying-to-programmatically-perform-click-on-non-visi