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

有些话、适合烂在心里 提交于 2019-12-25 03:21:56

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/27824237/how-to-perform-programmatic-click-on-a-item-in-a-recyclerview

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