helloimyourmind
helloimyourmind

Reputation: 994

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?

Upvotes: 7

Views: 6440

Answers (3)

duranun
duranun

Reputation: 331

try this for kotlin and viewBinding

 viewBinding.catList.post {
            val view = viewBinding.catList.findViewHolderForAdapterPosition(0)?.itemView?.findViewById<CheckBox>(R.id.catButton)
            view?.callOnClick()
        }

Upvotes: 2

ht xf
ht xf

Reputation: 103

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.

Upvotes: 10

Steve
Steve

Reputation: 826

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.

Upvotes: 3

Related Questions