Null pointer exception when trying to programmatically perform click on non visible Recycler view item

旧时模样 提交于 2019-12-19 10:38:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!