This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

directory

  • The problem
  • To solve

The problem

Q: Can RecyclerView set click events for each object?

Stackoverflow address: stackoverflow.com/questions/2…

Did anyone use RecyclerView and find a way to set the onClickListener method for every item in RecyclerView? I’m going to set up a listener for each project’s layout element, but that seems a bit cumbersome, and I’m sure there’s a way to make RecyclerView listen for onClick events, but I can’t think of one yet.

To solve

Since the official RecyclerView API has changed significantly, I wouldn’t be surprised if you wanted to create a separate OnClickListener for each element item. However, it is not difficult. You can use recyclerView. Adapter in the implementation, the reference code is as follows:

private final OnClickListener mOnClickListener = new MyOnClickListener();

@Override
public MyViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) {
    View view = LayoutInflater.from(mContext).inflate(R.layout.myview, parent, false);
    view.setOnClickListener(mOnClickListener);
    return new MyViewHolder(view);
}
Copy the code

The onClick method is defined as follows:

@Override
public void onClick(final View view) {
    int itemPosition = mRecyclerView.getChildLayoutPosition(view);
    String item = mList.get(itemPosition);
    Toast.makeText(mContext, item, Toast.LENGTH_LONG).show();
}
Copy the code