How to apply the onClick Listener in RecyclerView

Asked 2 years ago, Updated 2 years ago, 96 views

I put an onClick event in RecyclerView to apply onClickListener to each item, but it doesn't work properly. How shall I do it?

android java android-5.0-lollipop recyclerview

2022-09-22 22:29

1 Answers

In RecyclerView, there is OnItemTouchListener, and you can change it a little bit and put OnClickListener in each item. Go to RecyclerView.Adapter Implementation

private final OnClickListener mOnClickListener = new MyOnClickListener();

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

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


2022-09-22 22:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.