RecyclerView programmatically click

自闭症网瘾萝莉.ら 提交于 2019-12-23 17:11:01

问题


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?


回答1:


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.




回答2:


I just had a similar question with yours.And I had solve it! Here is 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 the specific item, then perform click. Because the doc say

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

But I know the adapter has the data, so scroll to it first, and findViewHolderForAdapterPositionwill not be null.

One more thing, I do not know how you use the RecyclerView. In my application, I use it in a fragment, and I don not know why we should delay it scroll and perform click. (Maybe it is because of the life circle?).But this really works.



来源:https://stackoverflow.com/questions/33336677/recyclerview-programmatically-click

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