user3182266
user3182266

Reputation: 1330

How to perform programmatic click on a item in a RecyclerView?

Hi I have a app that uses a Recycler view to display a bunch of items. Now I want to run an android test on the list but I don't know how to set a programmatic click on a given item. Can anyone tell me how to achieve this?

Upvotes: 0

Views: 3570

Answers (1)

droidpl
droidpl

Reputation: 5892

You have to implement it from scratch. The RecyclerView lacks for some of the awesome features that a ListView provides by default. Given this, in the adapter you have to declare an interface for the Observer between Fragment/Activity and the RecyclerView.

The correct method to attach this click event is onBindViewHolder. Then in the adapter you keep the reference to the CustomListener or the View.OnClickListener.

Here is a quick example on how to do this:

@Override
public void onBindViewHolder(SearchListAdapter.ViewHolder holder, final int position) {
    //Item clicked
    holder.mParent.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Select or deselect
            mListener.notify(holder, position);
        }
    });
}

And the ViewHolder should be like:

public class ViewHolder extends RecyclerView.ViewHolder {

    private View mParent;

    public ViewHolder(View itemView) {
        super(itemView);
        mParent = itemView;
    }
}

Where mParent is the current row View.

Upvotes: 1

Related Questions