RecyclerView programmatically click
Asked Answered
E

3

7

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?

Estell answered 26/10, 2015 at 0:24 Comment(1)
You should see this answer RecyclerView onClickClericalism
I
3

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.

Imprisonment answered 26/10, 2015 at 0:33 Comment(1)
i have tried your solution but i m getting null pointer exception when the item is not visibleSquad
L
10

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.

Limbus answered 27/6, 2016 at 9:54 Comment(0)
I
3

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.

Imprisonment answered 26/10, 2015 at 0:33 Comment(1)
i have tried your solution but i m getting null pointer exception when the item is not visibleSquad
S
2

try this for kotlin and viewBinding

 viewBinding.catList.post {
            val view = viewBinding.catList.findViewHolderForAdapterPosition(0)?.itemView?.findViewById<CheckBox>(R.id.catButton)
            view?.callOnClick()
        }
Surra answered 9/7, 2020 at 21:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.