Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 363
helloimyourmind Avatar asked Oct 26 '15 00:10

helloimyourmind


1 Answers

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.

like image 166
ht xf Avatar answered Sep 28 '22 16:09

ht xf